观察者模式
观察者模式有时也被称为发布/订阅模式,该模式定义了一种一对多的依赖关系,可以让多个观察者对象同时监听某一个主题对象,当主题对象的状态发生变化时,通知所有观察者对象,使它们能够自动更新自己。例如某个Text文本框的text属性绑定到X数据源上,当X数据源发生更改时自动同步更新Text的值。被观察者要维护一个观察者的List,逐个通知可能存在性能的问题(比如List很长,或者update的逻辑耗时等)。
//观察者接口public interface IWatcher { public void update(String str); }
//被观察者接口public interface IWatched { public void addWatcher(IWatcher watcher); public void removeWatcher(IWatcher watcher); public void notifyWatchers(String str); }
//具体的观察者public class ConcreteWatcher implements IWatcher { @Override public void update(String str) { System.out.println(str); } }
//具体的被观察者public class ConcreteWatched implements IWatched { private List<IWatcher> watchers = new ArrayList<>(); @Override public void addWatcher(IWatcher watcher) { watchers.add(watcher); } @Override public void removeWatcher(IWatcher watcher) { watchers.remove(watcher); } @Override public void notifyWatchers(String str) { // 通知观察者 for (IWatcher iWatcher : watchers) { iWatcher.update(str); } } }
package ObserverPattern; public class Main { public static void executeObserverPattern() { System.out.println("Observer Pattern:"); IWatched watched = new ConcreteWatched(); IWatcher watcher1 = new ConcreteWatcher(); IWatcher watcher2 = new ConcreteWatcher(); ConcreteWatcher watcher3 = new ConcreteWatcher(); watched.addWatcher(watcher1); watched.addWatcher(watcher2); watched.addWatcher(watcher3); watched.notifyWatchers("Hello World!!!"); } }
时间: 2024-09-29 22:19:35