又叫发布-订阅者模式,或者模型-视图模式。
在被观察者的状态发生变化时,系统基于事件驱动理论将其状态通知到订阅其状态的观察者对象中,以完成状态的修改和事件传播。
(1)定义抽象主题
public abstract class Subject{ protected List<Observer> observers = new ArrayList<>(); public void add(Observer observer){ observers.add(observer); } public void remove(Observer observer){ observers.remove(observer); } public abstract void notifyObserver(String message); }
(2)定义具体主题
public class ConcreteSubject extends Subject{ private final static Log logger = LogFactory.getLog(this.getClass()); @Override public void notifyObserver(String message){ for (Observer obs:observers){ logger.info("notity observer "+message+" change..."); obs.dataChange(message); } } }
(3)定义观察者
public interface Observer{ void dataChange(String message); } public class ConcreteObserver implements Observer{ private final static Log logger = LogFactory.getLog(this.getClass()); @Override public void dataChange(String message){ logger.info("receivd message: "+message); } }
(4)使用观察者模式
public static void main(String[] args){ Subject subject = new ConcreteSubject(); Observer obs = new ConcreteObserver(); subject.add(obs); subject.notifyObserver("data1"); }