一、概述
观察者模式类似于邮件订阅和RSS订阅,当我们浏览一些博客或wiki时,经常会看到RSS图标,就这的意思是,当你订阅了该文章,如果后续有更新,会及时通知你。其实,简单来讲就一句话:当一个对象变化时,其它依赖该对象的对象都会收到通知,并且随着变化!对象之间是一种一对多的关系。先来看看关系图:
二、代码实现
一个Observer接口: Observer.java
public interface Observer{ public void update();
}
两个实现类: Observer1.java、Observer2.java
public class Observer1 implements Observer{ @Override
public void update(){
System.out.println("observer1 has received...");
} }
public class Observer2 implements Observer{ @Override
public void update(){
System.out.println("observer2 has received...");
} }
Subject接口: Subject.java
public interface Subject{ /*增加观察者*/
public void add(Observer observer); /*删除观察者*/
public void del(Observer observer); /*通知所有的观察者*/
public void notifyObservers(); /*自身的操作*/
public void operation();
}
实现类: AbstractSubject.java、MySubject.java
public class AbstractSubject implements Subject{ private List<Observer> list = new ArrayList<Observer>(); @Override
public void add(Observer observer){
list.add(observer);
} @Override
public void del(Observer observer){
list.remove(observer);
} @Override
public void notifyObservers(){
for(Observer observer : list){
observer.update();
}
} @Override
public void operation(){ }
}
public class MySubject extends AbstractSubject{ @Override
public void operation(){
System.out.println("update self......");
notifyObservers();
}
}
测试:
@Test
public void testObserver(){
MySubject mySubject = new MySubject();
mySubject.add(new Observer1());
mySubject.add(new Observer2());
mySubject.operation();
}
结果:
update self......
observer1 has received...
observer2 has received...