这是一种很常见的模式,主要是在两种对象之间建立一定的联系,当一方(被观察者)发生改变时,另一方(观察者)可以及时获得通知。既可以一对一也可以一对多.简单实现:
观察者抽象类:
public abstract class Observer {
public abstract void update(String msg);
}
观察者实现类
public class ObserverA extends Observer{
@Override
public void update(String msg) {
System.out.println("ObserverA: " + msg);
}
}
public class ObserverB extends Observer{
@Override
public void update(String msg) {
System.out.println("ObserverB: " + msg);
}
}
public class ObserverC extends Observer{
@Override
public void update(String msg) {
System.out.println("ObserverC: " + msg);
}
}
被观察者:
public class Observable {
private ArrayList<Observer> observers = new ArrayList<>();
public void sendMsg(String msg) {
notifyAll(msg);
}
public void addObserver(Observer observer) {
observers.add(observer);
}
private void notifyAll(String msg) {
for (Observer observer : observers) {
observer.update(msg);
}
}
}
测试类
public static void main(String[] args) {
Observable observable = new Observable();
ObserverA observerA = new ObserverA();
ObserverB observerB = new ObserverB();
ObserverC observerC = new ObserverC();
observable.addObserver(observerA);
observable.addObserver(observerB);
observable.addObserver(observerC);
observable.sendMsg("hello");
}
网友评论