本示例一共提供四个接口或类,如下类图所示:
第一步:定义抽象观察者角色
public interface Observer {
void update(String msg);
}
第二步:定义抽象被观察者角色
public interface Observable {
void addObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers(String msg);
}
第三步:定义具体观察者
public class ConcreteObserver implements Observer {
@Override
public void update(String msg) {
System.out.println(msg);
}
}
第四步:定义具体被观察者
public class ConcreteObservable implements Observable {
private List<Observer> observers = new ArrayList<>();
@Override
public void addObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers(String msg) {
for(Observer observer : observers)
observer.update(msg);
}
}
第五步:定义测试方法,具体代码如下:
public static void main(String[] args) {
System.out.println("run java");
Observable observable = new ConcreteObservable();
Observer observer1 = new ConcreteObserver();
Observer observer2 = new ConcreteObserver();
Observer observer3 = new ConcreteObserver();
observable.addObserver(observer1);
observable.addObserver(observer2);
observable.addObserver(observer3);
observable.notifyObservers("HelloWorld");
}
运行程序,结果如下图所示: