观察者模式
设计模式的意义在于:面向业务内容、业务数据结构和系统架构,高内聚低耦合、优雅的将平面逻辑立体化。
1 package designPattern; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 /** 6 * 观察者模式 7 * @author Administrator 8 */ 9 public class B19_ObserverTest { 10 11 /** 12 * 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。 13 */ 14 public static void main(String[] args) { 15 Policeman huangpuPoliceman=new HuangPuPoliceman(); 16 Policeman tianhePoliceman=new TianHePoliceman(); 17 Citizen c1=new HuangPuCitizen(); 18 Citizen c2=new TianHeCitizen(); 19 20 c1.register(huangpuPoliceman); 21 c1.register(tianhePoliceman); 22 c1.sendMessage("normal"); 23 24 c2.register(tianhePoliceman); 25 c2.sendMessage("unnormal"); 26 } 27 } 28 //subject 目标知道它的观察者。可以有任意多个观察者观察同一个目标。提供注册和删除观察者对象的接口。 29 abstract class Citizen { 30 31 @SuppressWarnings("rawtypes") 32 List pols; 33 34 String help = "normal"; 35 36 public void setHelp(String help) { 37 this.help = help; 38 } 39 40 public String getHelp() { 41 return this.help; 42 } 43 44 abstract void sendMessage(String help); 45 46 @SuppressWarnings("rawtypes") 47 public void setPolicemen() { 48 this.pols = new ArrayList(); 49 } 50 51 @SuppressWarnings("unchecked") 52 public void register(Policeman pol) { 53 this.pols.add(pol); 54 } 55 56 public void unRegister(Policeman pol) { 57 this.pols.remove(pol); 58 } 59 } 60 //observer 61 interface Policeman { 62 63 void action(Citizen ci); 64 } 65 //concreteSubject 66 class HuangPuCitizen extends Citizen { 67 68 public HuangPuCitizen() { 69 setPolicemen(); 70 } 71 72 public HuangPuCitizen(Policeman pol) { 73 setPolicemen(); 74 register(pol); 75 } 76 77 public void sendMessage(String help) { 78 setHelp(help); 79 for(int i = 0; i < pols.size(); i++) { 80 Policeman pol = (Policeman)pols.get(i); 81 //通知警察行动 82 pol.action(this); 83 } 84 } 85 } 86 class TianHeCitizen extends Citizen { 87 public TianHeCitizen() { 88 setPolicemen(); 89 } 90 91 public TianHeCitizen(Policeman pol) { 92 setPolicemen(); 93 register(pol); 94 } 95 96 public void sendMessage(String help) { 97 setHelp(help); 98 for (int i = 0; i < pols.size(); i++) { 99 Policeman pol =(Policeman)pols.get(i); 100 //通知警察行动 101 pol.action(this); 102 } 103 } 104 } 105 106 //concreteObserver 107 class HuangPuPoliceman implements Policeman { 108 109 public void action(Citizen ci) { 110 String help = ci.getHelp(); 111 if (help.equals("normal")) { 112 System.out.println("黄埔警察:一切正常, 不用出动"); 113 } 114 if (help.equals("unnormal")) { 115 System.out.println("有犯罪行为, 黄埔警察出动!"); 116 } 117 } 118 } 119 class TianHePoliceman implements Policeman { 120 121 public void action(Citizen ci) { 122 String help = ci.getHelp(); 123 if (help.equals("normal")) { 124 System.out.println("天河警察:一切正常, 不用出动"); 125 } 126 if (help.equals("unnormal")) { 127 System.out.println("有犯罪行为, 天河警察出动!"); 128 } 129 } 130 }
环境:JDK1.6,MAVEN,tomcat,eclipse
源码地址:https://files.cnblogs.com/files/xiluhua/designPattern.rar
欢迎亲们评论指教。