标签:cas isp 京东商城 接口 依赖 运行 size ESS wrapper
?
public interface Subject { void registerObserver(Observer observer); void removeObserver(Observer observer); void notifyObservers(); }public class LogitechSupplier implements Subject { Vector<Observer> observers; String message; public LogitechSupplier(){ observers = new Vector<>(); } @Override public void registerObserver(Observer observer) { observers.addElement(observer); } @Override public void removeObserver(Observer observer) { observers.removeElement(observer); } @Override public void notifyObservers() { for(Observer observer:observers){ observer.update(message); } } public void messageChanged(String message){ this.message=message; notifyObservers(); } } public interface Observer { void update(Object args); } public class TBShop implements Observer { Subject subject; public TBShop(Subject subject) { this.subject = subject; subject.registerObserver(this); } @Override public void update(Object args) { System.out.println("天猫商城收到消息:"+args); } } public class JDShop implements Observer { Subject subject;//通过持有主题,可以从主题拉取数据 public JDShop(Subject subject){ this.subject=subject; subject.registerObserver(this); } @Override public void update(Object args) { System.out.println("京东商城收到消息:"+args); } }
public class ObserverPatternTestDemo { public static void main(String args[]){ //获取主题 LogitechSupplier logitechSupplier = new LogitechSupplier(); //观察者注册 Observer jdShop = new JDShop(logitechSupplier); Observer tbShop = new TBShop(logitechSupplier); //主题向观察者推送消息 logitechSupplier.messageChanged("新鼠标到货了!"); logitechSupplier.messageChanged("机械键盘降价10%"); } }
观察者模式
原文地址:https://www.cnblogs.com/camcay/p/12331024.html