设计模式学习之观察者模式
1.名词解释
观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态变化时,会通知所有观察者对象,使它们能够自动更新自己。
?
2.代码示例
通知者接口package DesignPattern.ObserverPattern;public interface IObserver {public void updateState();}
?
观察者接口package DesignPattern.ObserverPattern;public interface IObserver {public void updateState();}
?
实际通知者类package DesignPattern.ObserverPattern;import java.util.ArrayList;import java.util.List;public class Secretary implements ISubject {private List<IObserver> obsList = new ArrayList();@Overridepublic void addObserver(IObserver o) {obsList.add(o);}@Overridepublic void delObserver(IObserver o) {obsList.remove(o);}@Overridepublic void notifyObserver() {if(obsList != null && obsList.size() > 0) {int size = obsList.size();for(int i = 0; i < size; i++) {IObserver observer = obsList.get(i);observer.updateState();}}}}
?
股票观察者package DesignPattern.ObserverPattern;public class StockObserver implements IObserver {@Overridepublic void updateState() { System.out.println("Boss is coming back, go to work now.");}}
?
玩游戏观察者package DesignPattern.ObserverPattern;public class PlayGameObserver implements IObserver {@Overridepublic void updateState() { System.out.println("It's time to work now.");}}
?
?
主控程序package DesignPattern.ObserverPattern;public class Client {public static void main(String[] args) {Secretary secretary = new Secretary();StockObserver stockObserver = new StockObserver();PlayGameObserver playGameObserver = new PlayGameObserver();secretary.addObserver(stockObserver);secretary.addObserver(playGameObserver);secretary.notifyObserver();}}
?