标签:
观察者模式:
观察者模式定义了一种一对多的依赖关系,当一个对象改变状态时,它的所有依赖者都会受到通知,并自动更新。
注意: 观察者模式会造成内存泄漏,一定要记得取消订阅
UML关系图如下:
观察者模式提供了一种对象设计,让主题和观察者之间松耦合。
代码实现
首先定义抽象的观察者:
public interface Watcher { void update(String str); }定义被观察者:
public interface Watched{ void addWatcher(Watcher watcher); void removeWatcher(Watcher watcher); void notifyWatchers(String str); }
public class ConcreteWatcher implements Watcher{ @Override public void update(String str){ System.out.println(str); } }定义具体的被观察者:
import java.util.ArrayList; import java.util.List; public class ConcreteWatched implements Watched{ // 存放观察者 private List<Watcher> list = new ArrayList<Watcher>(); @Override public void addWatcher(Watcher watcher){ list.add(watcher); } @Override public void removeWatcher(Watcher watcher) { list.remove(watcher); } @Override public void notifyWatchers(String str){ // 自动调用实际上是主题进行调用的 for (Watcher watcher : list){ watcher.update(str); } } }书写测试类:
public class Test{ public static void main(String[] args){ Watched girl = new ConcreteWatched(); Watcher watcher1 = new ConcreteWatcher(); Watcher watcher2 = new ConcreteWatcher(); Watcher watcher3 = new ConcreteWatcher(); girl.addWatcher(watcher1); girl.addWatcher(watcher2); girl.addWatcher(watcher3); girl.notifyWatchers("开心"); } }其实,如果大家做过Android开发的话,Android里面大量用了观察者模式,用textWatcher,eventbus等。
标签:
原文地址:http://blog.csdn.net/xiangzhihong8/article/details/52075547