观察者模式即发布订阅模式,发布者发布信息,订阅者获取信息。当发布者改变状态时,依赖它的订阅者会收到通知并自动更新。
角色划分
抽象被观察者角色:提供增加、删除、通知观察者的接口。
具体被观察者角色:用一个集合保存所有被观察者对象,实现增加、删除、通知观察者的功能。
抽象观察者角色:为所有的具体观察者定义一个接口,在得到主题通知时更新自己。
具体观察者角色:实现抽象观察者角色所需要的更新接口。
类图
代码示例
抽象被观察者角色:Obverable
public interface Obverable {
public void registObserver(Observer observer);
public void removeObserver(Observer observer);
public void notifyObserver();
}
具体被观察者角色:Magazine
public class Magazine implements Obverable {
private List<Observer> observers = new ArrayList<Observer>();
private String msg;
@Override
public void registObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObserver() {
for (Observer observer: observers) {
observer.update(msg);
}
}
public void publishNews(String msg) {
this.msg = msg;
this.notifyObserver();
}
}
抽象观察者角色:Observer
public interface Observer {
public void update(String msg);
}
具体观察者角色:ReaderA、ReaderB、ReaderC
public class ReaderA implements Observer {
@Override
public void update(String msg) {
System.out.println("ReaderA, msg="+msg);
}
}
public class ReaderB implements Observer {
@Override
public void update(String msg) {
System.out.println("ReaderB, msg="+msg);
}
}
public class ReaderC implements Observer {
@Override
public void update(String msg) {
System.out.println("ReaderC, msg="+msg);
}
}
在ObserverTest中调用Magazine并注册Reader,Magazine发布消息后,各Reader能收到消息
public class ObserverTest {
public static void main(String[] args) {
Magazine magazine = new Magazine();
ReaderA readerA = new ReaderA();
ReaderB readerB = new ReaderB();
ReaderC readerC = new ReaderC();
magazine.registObserver(readerA);
magazine.registObserver(readerB);
magazine.registObserver(readerC);
magazine.publishNews("msg1");
magazine.removeObserver(readerA);
magazine.publishNews("msg2");
}
}
运行结果如下:
ReaderA, msg=msg1
ReaderB, msg=msg1
ReaderC, msg=msg1
ReaderB, msg=msg2
ReaderC, msg=msg2