四、类图
五、示例
Subject
package cn.lynn.observer; import java.util.ArrayList; import java.util.List; public abstract class Citizen { protected List<Policeman> polices; private String action = "normal"; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public void setPolices() { polices = new ArrayList<Policeman>(); } public void register(Policeman police) { polices.add(police); } public void unregister(Policeman police) { polices.remove(police); } public abstract void notify(String action); }Observer
package cn.lynn.observer; public interface Policeman { public void setOut(Citizen citizen); }ConcreteSubject
package cn.lynn.observer; public class DongHuCitizen extends Citizen { public DongHuCitizen(Policeman police) { setPolices(); register(police); } @Override public void notify(String action) { setAction(action); for (int i = 0; i < polices.size(); i++) { Policeman police = polices.get(i); police.setOut(this); } } }
package cn.lynn.observer; public class NanHuCitizen extends Citizen { public NanHuCitizen(Policeman police) { setPolices(); register(police); } @Override public void notify(String action) { setAction(action); for (int i = 0; i < polices.size(); i++) { Policeman police = polices.get(i); police.setOut(this); } } }ConcreteObserver
package cn.lynn.observer; public class DongHuPoliceman implements Policeman { @Override public void setOut(Citizen citizen) { String action = citizen.getAction(); if(action.equals("normal")) { System.out.println("行为一切正常"); } else if(action.equals("unnormal")) { System.out.println("有偷窃行为,东湖警察出动!"); } } }
package cn.lynn.observer; public class NanHuPoliceman implements Policeman { @Override public void setOut(Citizen citizen) { String action = citizen.getAction(); if(action.equals("normal")) { System.out.println("行为一切正常"); } else if(action.equals("unnormal")) { System.out.println("有抢劫行为,南湖警察出动!"); } } }Client
package cn.lynn.observer; public class Client { public static void main(String[] args) { Policeman dhPolice = new DongHuPoliceman(); Policeman nhPolice = new NanHuPoliceman(); Citizen citizen = new DongHuCitizen(dhPolice); citizen.notify("normal"); citizen.notify("unnormal"); citizen = new NanHuCitizen(nhPolice); citizen.notify("normal"); citizen.notify("unnormal"); } }Result
行为一切正常 有偷窃行为,东湖警察出动! 行为一切正常 有抢劫行为,南湖警察出动!