1.概述
观察者是定义对象间一对多一种依赖关系,在对象状态发生变化的时候可以通知依赖对象更新状态。
2.UML结构图
image.png3.代码实现:
观察者角色
public interface Observer {
void update();
}
被观察者角色
public class Subject {
private List<Observer> observers = new ArrayList<>();
public void register(Observer observer) {
if (!observers.contains(observer)) {
observers.add(observer);
}
}
public void unRegister(Observer observer) {
if (observers.contains(observer)) {
observers.remove(observer);
}
}
public void notifyObserver(Observer observer) {
for (Observer o :
observers) {
o.notify();
}
}
}
具体观察者角色
public class ConcreteObserverA implements Observer{
@Override
public void update() {
Logger.getLogger("ConcreteObserverA").info("update");
}
}
public class ConcreteObserverB implements Observer {
@Override
public void update() {
Logger.getLogger("ConcreteObserverB").info("update");
}
}
客户端
public class ObserverClient {
public void test() {
Subject subject = new Subject();
Observer observera = new ConcreteObserverA();
subject.register(observera);
Observer observerb = new ConcreteObserverB();
subject.register(observerb);
subject.notifyObserver(observerb);
}
}
网友评论