一般情况下,被依赖的对象叫作被观察者(Observable),依赖的对象叫作观察者(Observer)。
不过,在实际的项目开发中,这两种对象的称呼是比较灵活的,有各种不同的叫法,
比如:Subject-Observer、Publisher-Subscriber、Producer-Consumer、EventEmitter-EventListener、Dispatcher-Listener。
不管怎么称呼,只要应用场景符合刚刚给出的定义,都可以看作观察者模式。
消息通知体:
package com.lf.pattern.observer; public class Message { String msg;//通知信息 public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
Subject:
package com.lf.pattern.observer; public interface Subject { void registerObserver(Observer observer); void removeObserver(Observer observer); void notifyObservers(Message message); }
Observer:
package com.lf.pattern.observer; public interface Observer { void update(Message message); }
ConcreteSubject(观察者对象):
package com.lf.pattern.observer; import java.util.ArrayList; import java.util.List; public class ConcreteSubject implements Subject { private List<Observer> observers = new ArrayList<Observer>(); @Override public void registerObserver(Observer observer) { observers.add(observer); } @Override public void removeObserver(Observer observer) { observers.remove(observer); } @Override public void notifyObservers(Message message) { for (Observer observer : observers) { observer.update(message); } } }
被观察对象:
package com.lf.pattern.observer; public class ConcreteObserverOne implements Observer { @Override public void update(Message message) { //TODO: 获取消息通知,执行自己的逻辑... System.out.println("ConcreteObserverOne is notified."); } }
package com.lf.pattern.observer; public class ConcreteObserverTwo implements Observer { @Override public void update(Message message) { //TODO: 获取消息通知,执行自己的逻辑... System.out.println("ConcreteObserverTwo is notified."); } }
使用用例:
package com.lf.pattern.observer; public class UserDemo { public static void main(String[] args) { ConcreteSubject subject = new ConcreteSubject(); subject.registerObserver(new ConcreteObserverOne()); subject.registerObserver(new ConcreteObserverTwo()); subject.notifyObservers(new Message()); } }