概述:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
适用性:
1.当一个抽象模型有两个方面,其中一个方面依赖于另一方面。
将这二者封装在独立的对象中以使它们可以各自独立地改变和复用。
2.当对一个对象的改变需要同时改变其它对象,而不知道具体有多少对象有待改变。
3.当一个对象必须通知其它对象,而它又不能假定其它对象是谁。
参与者:
1.Subject(目标) 目标知道它的观察者。可以有任意多个观察者观察同一个目标。 提供注册和删除观察者对象的接口。 2.Observer(观察者) 为那些在目标发生改变时需获得通知的对象定义一个更新接口。 3.ConcreteSubject(具体目标) 将有关状态存入各ConcreteObserver对象。 当它的状态发生改变时,向它的各个观察者发出通知。 4.ConcreteObserver(具体观察者) 维护一个指向ConcreteSubject对象的引用。 存储有关状态,这些状态应与目标的状态保持一致。 实现Observer的更新接口以使自身状态与目标的状态保持一致
类图:
例子
1 //Subject 2 3 public abstract class Citizen { 4 5 List pols; 6 7 String help = "normal"; 8 9 public void setHelp(String help) { 10 this.help = help; 11 } 12 13 public String getHelp() { 14 return this.help; 15 } 16 17 abstract void sendMessage(String help); 18 19 public void setPolicemen() { 20 this.pols = new ArrayList(); 21 } 22 23 public void register(Policeman pol) { 24 this.pols.add(pol); 25 } 26 27 public void unRegister(Policeman pol) { 28 this.pols.remove(pol); 29 } 30 }
1 //Observer 2 3 public interface Policeman { 4 5 void action(Citizen ci); 6 }
1 //ConreteSubject 2 3 public class HuangPuCitizen extends Citizen { 4 5 public HuangPuCitizen(Policeman pol) { 6 setPolicemen(); 7 register(pol); 8 } 9 10 public void sendMessage(String help) { 11 setHelp(help); 12 for(int i = 0; i < pols.size(); i++) { 13 Policeman pol = pols.get(i); 14 //通知警察行动 15 pol.action(this); 16 } 17 } 18 } 19 20 public class TianHeCitizen extends Citizen { 21 22 public TianHeCitizen(Policeman pol) { 23 setPolicemen(); 24 register(pol); 25 } 26 27 public void sendMessage(String help) { 28 setHelp(help); 29 for (int i = 0; i < pols.size(); i++) { 30 Policeman pol = pols.get(i); 31 //通知警察行动 32 pol.action(this); 33 } 34 } 35 }
1 //ConcreteObserver 2 3 public class HuangPuPoliceman implements Policeman { 4 5 public void action(Citizen ci) { 6 String help = ci.getHelp(); 7 if (help.equals("normal")) { 8 System.out.println("一切正常, 不用出动"); 9 } 10 if (help.equals("unnormal")) { 11 System.out.println("有犯罪行为, 黄埔警察出动!"); 12 } 13 } 14 } 15 16 17 public class TianHePoliceman implements Policeman { 18 19 public void action(Citizen ci) { 20 String help = ci.getHelp(); 21 if (help.equals("normal")) { 22 System.out.println("一切正常, 不用出动"); 23 } 24 if (help.equals("unnormal")) { 25 System.out.println("有犯罪行为, 天河警察出动!"); 26 } 27 } 28 }
1 //Test module 2 3 public class Test{ 4 5 public static void main(String[] args) { 6 Policeman thPol = new TianHePoliceman(); 7 Policeman hpPol = new HuangPuPoliceman(); 8 9 Citizen citizen = new HuangPuCitizen(hpPol); 10 citizen.sendMessage("unnormal"); 11 citizen.sendMessage("normal"); 12 13 System.out.println("==========="); 14 15 citizen = new TianHeCitizen(thPol); 16 citizen.sendMessage("normal"); 17 citizen.sendMessage("unnormal"); 18 } 19 }
1 //Result 2 3 有犯罪行为, 黄埔警察出动! 4 一切正常, 不用出动 5 =========== 6 一切正常, 不用出动 7 有犯罪行为, 天河警察出动!
原文:http://www.cnblogs.com/izhanjun/p/4184426.html