觀察者模式【行為模式】
阿新 • • 發佈:2018-12-23
class call nts mat 依賴關系 接口 lis 通知 觀察
觀察者模式
Define a one-to-many dependency between objects so that when one object change state,
all its dependents are notified and updated automatically.
定義對象間一種一對多的依賴關系,這樣,當一的一方狀態改變時,所有它的依賴者都會被自動通知。
public class Observer { /** * 觀察者模式: * Define a one-to-many dependency between objects so that when one object change state, * all its dependents are notified and updated automatically. * 定義對象間一種一對多的依賴關系,這樣,當一的一方狀態改變時,所有它的依賴者都會被自動通知。 */ @Test public void all() { final Student student = Student.builder().name("二狗子").build(); final Monitor monitor = Monitor.builder().name("monitor").build(); final Teacher teacher = Teacher.builder().name("teacher").build(); student.addObserver(monitor); student.addObserver(teacher); student.play(); } } /** * 1)觀察者需要觀察的事件或行為 */ interface IObserver { void inform(String event); } /** * 2)被觀察者對觀察者的操作接口 */ interface IObserverOperate { void addObserver(IObserver observer); void removeObserver(IObserver observer); void notifyAll(String target); } /** * 3)具體的觀察者實現 */ @Builder @Slf4j class Monitor implements IObserver { private final String name; @Override public void inform(String event) { log.info("{} {}", name, event); } } /** * 4)具體的觀察者實現 */ @Builder @Slf4j class Teacher implements IObserver { private final String name; @Override public void inform(String event) { log.info("{} {}", name, event); } } /** * 4)具體的被觀察者實現,實現了觀察者管理接口 */ @Builder class Student implements IObserverOperate { private final String name; @Default private final List<IObserver> observers = Lists.newArrayList(); @Override public void addObserver(IObserver observer) { observers.add(observer); } @Override public void removeObserver(IObserver observer) { observers.remove(observer); } @Override public void notifyAll(String target) { observers.forEach(observer -> observer.inform(target)); } public void play() { /** * 一旦主體狀態變化,立即通知所有的觀察者 */ final String event = name + " is plaing"; notifyAll(event); } }
觀察者模式【行為模式】