package 设计模式.观察者模式;/** * @author baoyou E-mail:curiousby@163.com * @version 创建时间:2021年05月19日2021年05月19日 上午10:33:22 * des: */public interface Watcher { public void update(String str);}
package 设计模式.观察者模式;/** * @author baoyou E-mail:curiousby@163.com * @version 创建时间:2021年05月19日2021年05月19日 上午10:33:33 * des: */public interface Watched { public void addWatcher(Watcher watcher); public void removeWatcher(Watcher watcher); public void notifyWatchers(String str);}
package 设计模式.观察者模式;import java.util.ArrayList;import java.util.List;/** * @author baoyou E-mail:curiousby@163.com * @version 创建时间:2021年05月19日2021年05月19日 上午10:34:58 * des: */public class ConcreteWatched implements Watched{private List list = new ArrayList();@Overridepublic void addWatcher(Watcher watcher) { list.add(watcher);}@Overridepublic void removeWatcher(Watcher watcher) { list.remove(watcher);}@Overridepublic void notifyWatchers(String str) { for (Watcher watcher : list) { watcher.update(str); }}}
package 设计模式.观察者模式;/** * @author baoyou E-mail:curiousby@163.com * @version 创建时间:2021年05月19日2021年05月19日 上午10:34:33 * des: */public class ConcreteWatcher implements Watcher {@Overridepublic void update(String str) { System.out.println(str);}}
package 设计模式.观察者模式;/** * @author baoyou E-mail:curiousby@163.com * @version 创建时间:2021年05月19日2021年05月19日 上午10:28:36 * des: */public class ObserverTest {public static void main(String[] args) { Watched weather = new ConcreteWatched(); Watcher observer1 = new ConcreteWatcher(); Watcher observer2 = new ConcreteWatcher(); Watcher observer3 = new ConcreteWatcher(); weather.addWatcher(observer1); weather.addWatcher(observer2); weather.addWatcher(observer3); weather.notifyWatchers("大风暴 要来了,船员们站好自己的岗位");}}
捐助开发者
在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。
谢谢您的赞助,我会做的更好!