观察者模式
概述:
有两种对象:主题、观察者。
场合:主题的状态变化时,所有观察者都能够获知。
以下是个人的分析与理解:
观察者和主题存在一对多的对应关系,即一个主题可被过多个观察者关注。这里很容易就可以联想到主题应当可以管理一组观察者,并提供如下操作:
1. 注册某个观察者。
2. 删除某个观察者。
3. 状态变化时,通知所有观察者。
当主题通知观察者时,每个没观察者又应当有属于自己的“反应”,没错,使用多态即可!!
实现:
Subject接口:
1 package Observer; 2 /* 3 * Subject Interface 4 */ 5 public interface Subject { 6 public void registerObserver(Observer o); 7 public void removeObserver(Observer o); 8 public void notifyAllObservers(); 9 }
Observer接口:
1 package Observer; 2 /* 3 * Observer interface 4 */ 5 public interface Observer { 6 public void update(int state); 7 }
Subject实现类:
1 package Observer; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 public class SubjectImpl implements Subject { 7 8 private List<Observer> observers; 9 private int state; 10 11 public SubjectImpl () { 12 observers = new ArrayList<Observer>(); 13 } 14 15 @Override 16 public void registerObserver(Observer o) { 17 // TODO Auto-generated method stub 18 observers.add(o); 19 } 20 21 @Override 22 public void removeObserver(Observer o) { 23 // TODO Auto-generated method stub 24 if (observers.contains(o)) { 25 observers.remove(o); 26 } 27 } 28 29 @Override 30 public void notifyAllObservers() { 31 // TODO Auto-generated method stub 32 for (Observer o: observers) { 33 o.update(state); 34 } 35 } 36 37 public void setState(int s) { 38 this.state = s; 39 notifyAllObservers(); 40 } 41 42 }
Observer实现类:
1 package Observer; 2 3 public class ObserverImpl implements Observer { 4 5 private String name; 6 7 public ObserverImpl (String name) { 8 this.name = name; 9 } 10 11 @Override 12 public void update(int state) { 13 // TODO Auto-generated method stub 14 System.out.println(name + " has received the subject state: " + state); 15 } 16 17 }
调用方式:
1 package org.wgx.pattern.observer; 2 3 public class Demo { 4 5 /** 6 * @param args 7 */ 8 public static void main(String[] args) { 9 // TODO Auto-generated method stub 10 SubjectImpl sub = new SubjectImpl(); 11 Observer o1 = new ObserverImpl("o1"); 12 Observer o2 = new ObserverImpl("o2"); 13 sub.registerObserver(o1); 14 sub.registerObserver(o2); 15 sub.setState(2); 16 } 17 18 }
o1 has received the subject state: 2
o2 has received the subject state: 2