一、概念
观察者模式(Observer Pattern):在对象之间定义一个一对多的依赖,当一个对象状态改变的时候,所有依赖的对象都会自动收到通知。
二、实现
这里举个电视剧订阅的例子,比如琅琊榜,我们订阅以后,每集更新都会通知到所有的订阅者。
1、被观察者
#TVPlayObservable
public interface TVPlayObservable {
void registerObserver(Observer observer);
void unRegisterObserver(Observer observer);
void notifyObservers(String newMsg);
}
#LangYaBangObservable
public class LangYaBangObservable implements TVPlayObservable {
List<Observer> observers = new ArrayList<>();
@Override
public void registerObserver(Observer observer) {
if (observer != null && !observers.contains(observer)) {
observers.add(observer);
}
}
@Override
public void unRegisterObserver(Observer observer) {
if (observer != null && observers.contains(observer)) {
observers.remove(observer);
}
}
@Override
public void notifyObservers(String newMsg) {
for (Observer observer : observers) {
observer.updateMessage(newMsg);
}
}
}
2、观察者
public interface Observer {
void updateMessage(String msg);
}
public class ObserverA implements Observer {
@Override
public void updateMessage(String msg) {
System.out.println("ObserverA - 新消息:" + msg);
}
}
public class ObserverB implements Observer {
@Override
public void updateMessage(String msg) {
System.out.println("ObserverB - 新消息:" + msg);
}
}
3、测试类
public class Client {
public static void main(String[] args) {
LangYaBangObservable langYaBangObservable = new LangYaBangObservable();
ObserverA observerA = new ObserverA();
ObserverB observerB = new ObserverB();
langYaBangObservable.registerObserver(observerA);
langYaBangObservable.registerObserver(observerB);
langYaBangObservable.notifyObservers("琅琊榜剧更新了,快来看啊!!!");
}
}
4、运行结果