标签:
观察者模式定义了对象之间一对多依赖,这样一来,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。
Observer
package com.singland.dp.observer; public interface Observer { public void update(Subject subject); }
MyObserver1
package com.singland.dp.observer; public class MyObserver1 implements Observer { @Override public void update(Subject subject) { System.out.println(String.format("MyObserver1: You are %s ?", subject.getMsg())); } }
MyObserver2
package com.singland.dp.observer; public class MyObserver2 implements Observer { @Override public void update(Subject subject) { System.out.println(String.format("MyObserver2: You are %s ?", subject.getMsg())); } }
Subject
package com.singland.dp.observer; import java.util.ArrayList; import java.util.List; public class Subject { private String msg; private List<Observer> observers = new ArrayList<Observer>(); public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public void registerObserver(Observer observer) { observers.add(observer); } public void removeObserver(Observer observer) { observers.remove(observer); } public void notifyObservers() { for (Observer observer : observers) { observer.update(this); } } }
MyTest
package com.singland.dp.observer; import org.junit.Test; public class MyTest { @Test public void test() { Subject subject = new Subject(); subject.registerObserver(new MyObserver1()); subject.registerObserver(new MyObserver2()); subject.setMsg("Linda"); subject.notifyObservers(); } }
当项目中的业务逻辑有关于出版者跟订阅者的概念的时候,我们应该第一时间想到使用观察者设计模式来处理问题,观察者设计模式应该是最常见的设计模式了,java甚至提供了内置的观察者设计模式供开发人员使用,但是java内置的观察者设计模式还是有一些局限性的:
标签:
原文地址:http://www.cnblogs.com/stonefeng/p/5693560.html