设计模式 - 观察者模式
/** * 观察者模块 * @author swt */ public interface Observer { /** * 更新数据 */ void update(); }
/** * 显示观察者 * @author swt */ public class DisplayObserver implements Observer { @Override public void update() { System.out.println("DisplayObserver.update"); } }
/** * 主题对象有3个基础操作:注册新的观察者、通知所有观察者更新数据、移除取消观察的观察者对象。 * @author swt */ public interface Subject { /** * 注册观察者 * @param observer 观察者 */ void addObserver(Observer observer); /** * 移除观察者 * @param observer 观察者 */ void removeObserver(Observer observer); /** * 通知所有观察者 */ void notifyObservers(); }
/** * 状态主题 * @author swt */ public class RelayStateSubject implements Subject { private List<Observer> observerList; private RelayStateSubject(){ observerList = new ArrayList<>(); System.out.println("RelayStateSubject.RelayStateSubject"); } static class RelayStateSubjectHolder { private static final RelayStateSubject INSTANCE = new RelayStateSubject(); } public static RelayStateSubject getInstance() { return RelayStateSubjectHolder.INSTANCE; } @Override public void addObserver(Observer observer) { observerList.add(observer); System.out.println("RelayStateSubject.addObserver"); } @Override public void removeObserver(Observer observer) { observerList.remove(observer); System.out.println("RelayStateSubject.removeObserver"); } @Override public void notifyObservers() { for (Observer o : observerList) { if(null == o) { continue; } o.update(); } System.out.println("RelayStateSubject.notifyObservers"); } /** * 改变状态 */ public void changeState() { notifyObservers(); } }
public class Main { public static void main(String[] args) { RelayStateSubject relayStateSubject = RelayStateSubject.getInstance(); relayStateSubject.addObserver(new DisplayObserver()); relayStateSubject.changeState(); System.out.println("Main.main"); } }
输出
RelayStateSubject.RelayStateSubject RelayStateSubject.addObserver DisplayObserver.update RelayStateSubject.notifyObservers Main.main