观察者模式
定义: 定义对象间一种一对多的依赖关系,使得当每一个对象改变状态,则所有依赖于它的对象都会得到通知并自动更新。
它能提供灵活的注册,移除,实现观察者与被观察者的解耦。
代码:
Subject :
public abstract class Subject { List<Obverser> list = new ArrayList<Obverser>(); void attach(Obverser o) { list.add(o); } void detach(Obverser o) { list.remove(o); } //通知所有 void notifyObverser() { for (Obverser o : list) { o.update(); } } //被观察者做什么事情,去通知所有人 abstract void doSomething(); }
SubjectEntity :
public class SubjectEntity extends Subject{ @Override void doSomething() { System.out.println("subject start do something"); notifyObverser(); } }
Obverser:
public interface Obverser { void update(); }
ObverserEntity1 :
public class ObverserEntity1 implements Obverser { @Override public void update() { System.out.println("obverser1 received message and start handle it"); } }
ObverserEntity2 :
public class ObverserEntity2 implements Obverser { @Override public void update() { System.out.println("obverser2 received message and start handle it"); } }
测试类:
public class TestObverser { public static void main(String[] args) { SubjectEntity sub = new SubjectEntity(); ObverserEntity1 obverser1 = new ObverserEntity1(); ObverserEntity2 obverser2 = new ObverserEntity2(); //注册两个观察者 System.out.println("action: register obverser1 and obverser2: "); sub.attach(obverser1); sub.attach(obverser2); sub.doSomething(); //移除一个观察者 System.out.println("action2: remove obverser2:"); sub.detach(obverser2); sub.doSomething(); } }
运行结果: