观察者模式(又叫订阅-发布模式):定义了一种一对多的关系,让多个观察者对象同时监听一个主题。当主题的状态发生变化时,会通知多个观察者,使他们能够自动更新自己。
/** * 抽象主题 * @author hsoft3 * */ public abstract class Subject { private List<Observer> list = new ArrayList<Observer>(); public void notifyObserver(){ for(Observer obs:list){ obs.update(); } } public void addObserver(Observer obs){ list.add(obs); } public boolean removeObserver(Subject sub){ return list.remove(sub); } /** * 获取主题状态 * @return */ public abstract String getSubjectState(); /** * 设置主题状态 * @param state */ protected abstract void setSubjectState(String state); }
/** * 抽象观察者 * @author hsoft3 * */ public abstract class Observer { private String name; private Subject sub; public Observer(String name, Subject sub){ this.name = name; this.sub = sub; //sub.addObserver(this); } public Subject getSubject(){ return this.sub; } public String getName() { return name; } public void setName(String name) { this.name = name; } public abstract void update(); }
/** * 具体主题 * @author hsoft3 * */ public class ConcreteSubject extends Subject { private String subjectState; @Override public String getSubjectState() { // TODO Auto-generated method stub return subjectState; } @Override protected void setSubjectState(String state) { // TODO Auto-generated method stub this.subjectState=state; } }
/** * 具体观察者 * @author hsoft3 * */ public class ConcreteObserver extends Observer { public ConcreteObserver(String name, Subject sub) { super(name, sub); } @Override public void update() { String str = String.format("观察者%s的状态是%s", super.getName(), super.getSubject().getSubjectState()); System.out.println(str); } }