1. 介绍
当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)
当一个对象被修改时,则会自动通知它的依赖对象(广播)。观察者模式属于行为型模式。
2. 类定义
定义观察者接口和被观察者抽象类
public interface Observer { void update(String msg); }
public abstract class Observerable { final List<Observer> observerList = new ArrayList<>(); void registerObserver(Observer observer) {} void removeObserver(Observer observer) {} void notifyObserver(String msg) {} }
定义实现被观察者的具体类
public class WechatServer extends Observerable{ @Override public void registerObserver(Observer observer) { if (!observerList.contains(observer)) { observerList.add(observer); System.out.println("add " + observer + " success"); } } @Override public void removeObserver(Observer observer) { if (!observerList.isEmpty()) { observerList.remove(observer); System.out.println("remove " + observer + " sucess"); } } @Override public void notifyObserver(String msg) { for (Observer observer : observerList) { observer.update(msg); } } }
定义实现观察者的2个具体类
public class PhoneObserver implements Observer{ @Override public void update(String msg) { System.out.println("phone receive:" + msg); } }
public class BookObserver implements Observer{ @Override public void update(String msg) { System.out.println("Book receive " + msg); } }
3.测试
public class ObserverTest { public static void main(String[] args) { Observerable observerable = new WechatServer(); Observer phone = new PhoneObserver(); Observer book = new BookObserver(); observerable.registerObserver(phone); observerable.registerObserver(book); observerable.notifyObserver("hello world"); observerable.removeObserver(book); observerable.notifyObserver("the second try"); observerable.removeObserver(book); observerable.notifyObserver("the second try"); } }
结果
add com.jihite.ObserverPattern.PhoneObserver@5674cd4d success add com.jihite.ObserverPattern.BookObserver@63961c42 success phone receive:hello world Book receive hello world remove com.jihite.ObserverPattern.BookObserver@63961c42 sucess phone receive:the second try remove com.jihite.ObserverPattern.BookObserver@63961c42 sucess phone receive:the second try |
4.总结
优点:
观察者和被观察者是抽象耦合的
建立一套触发机制
缺点
如果一个被观察者对象有很多的直接和间接的观察者的话,将所有的观察者都通知到会花费很多时间。
如果在被观察者之间有循环依赖的话,被观察者会触发它们之间进行循环调用,导致系统崩溃。在使用观察者模式是要特别注意这一点
虽然观察者模式可以随时使观察者知道所观察的对象发生了变化,但是观察者模式没有相应的机制使观察者知道所观察的对象是怎么发生变化的