设计模式笔记之三 观察者模式
?
import java.util.HashMap;import java.util.Map;/** * 主题类,被观察者对象 * */public class Subject {private Map<Observer, Observer> mapObserver = new HashMap<Observer, Observer>();/** * 注册方法,表示订阅 * @param observer */public void register(Observer observer) {mapObserver.put(observer, observer);}/** * 取消订阅 * @param observer */public void unregister(Observer observer) {mapObserver.remove(observer);}/** * 通知所有观察者 */public void notifyAllObserver() {for (Map.Entry<Observer, Observer> entry : mapObserver.entrySet()) {entry.getValue().update();}}}/** * 观察者接口 */public interface Observer {public void update();}/** * 观察者1 */public class ConcreteObserver1 implements Observer {@Overridepublic void update() {System.out.println("ConcreteObserver1 update...");}}/** * 观察者2 */public class ConcreteObserver2 implements Observer {@Overridepublic void update() {System.out.println("ConcreteObserver2 update...");}}/** * 观察者模式的使用 */public class TestObserver {/** * @param args */public static void main(String[] args) {Subject subject = new Subject();Observer observer1 = new ConcreteObserver1();Observer observer2 = new ConcreteObserver2();subject.register(observer1);subject.register(observer2);subject.notifyAllObserver();}}