JAVA设计模式之观察者模式

观察者模式:定义对象间的一种一对多的依赖关系。当一个对象的状态发生改变的时候,所有依赖于它的对象都得到通知并被自动更新。

简单例子:比如有两个人张三和李四订阅了气象台的天气推送消息。

 

  1 public class Subject 
  2 {
  3     private List<Observer> observers = new ArrayList<Observer>();
  4 
  5     public void attach(Observer observer)
  6     {
  7         observers.add(observer);
  8         observer.update(this);
  9     }
 10     
 11     public void detach(Observer observer)
 12     {
 13         observers.remove(observer);
 14     }
 15     
 16     protected void notifyObservers()
 17     {
 18         for(Observer observer: observers)
 19         {
 20             observer.update(this);
 21         }
 22     }
 23 }
 24 
 25 public interface Observer 
 26 {
 27     public void update(Subject subject);
 28 }
 29 
 30 public class ConcreteSubject extends Subject 
 31 {
 32     private String subjectState;
 33 
 34     public String getSubjectState() 
 35     {
 36         return subjectState;
 37     }
 38 
 39     public void setSubjectState(String subjectState) 
 40     {
 41         this.subjectState = subjectState;
 42         this.notifyObservers();
 43     }
 44 }
 45 
 46 import static java.lang.System.out;
 47 public class ConcreteObserver implements Observer
 48 {
 49     private String observerState;
 50 
 51     public void update(Subject subject) 
 52     {
 53         observerState = ((ConcreteSubject)subject).getSubjectState();
 54     }
 55     
 56     public void info()
 57     {
 58         out.println("我是:" + observerName);
 59         out.println("信息:" + observerState);
 60         out.println();
 61     }
 62     
 63     private String observerName;
 64 
 65     public void setObserverName(String observerName) 
 66     {
 67         this.observerName = observerName;
 68     }
 69 }
 70 
 71 public class Client 
 72 {
 73     public static void main(String[] args) 
 74     {
 75         ConcreteSubject weatherSubject = new ConcreteSubject();
 76         weatherSubject.setSubjectState("天气晴朗,25°");
 77         
 78         ConcreteObserver zhangsan = new ConcreteObserver();
 79         zhangsan.setObserverName("张三");
 80         
 81         ConcreteObserver lisi = new ConcreteObserver();
 82         lisi.setObserverName("李四");
 83         
 84         weatherSubject.attach(zhangsan);
 85         weatherSubject.attach(lisi);
 86         
 87         zhangsan.info();
 88         lisi.info();
 89         
 90         weatherSubject.detach(zhangsan);
 91         weatherSubject.setSubjectState("多云,20°");
 92         
 93         zhangsan.info();
 94         lisi.info();
 95     }
 96 }
 97 
 98 我是:张三
 99 信息:天气晴朗,25°
100 
101 我是:李四
102 信息:天气晴朗,25°
103 
104 我是:张三
105 信息:天气晴朗,25°
106 
107 我是:李四
108 信息:多云,20°

 

posted @ 2016-08-22 19:15  hxy_has_been_used  阅读(214)  评论(0编辑  收藏  举报