定义:
定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使他们能够自动更新自己。
结构:(书中图,侵删)
实例:
package designpattern.observer; public interface Fans { public void react(String result); }
package designpattern.observer; public class HomeFans implements Fans { @Override public void react(String result) { System.out.print("主场球迷:"); if (result.equals("win")) { System.out.println("Yes! 我们赢啦,主场就是牛批!!!"); } else { System.out.println("输了,哎..."); } } }
package designpattern.observer; public class AwayFans implements Fans { @Override public void react(String result) { System.out.print("客场球迷:"); if (result.equals("win")) { System.out.println("输了,哎..."); } else { System.out.println("Yes! 客场都赢啦,牛批!!!"); } } }
package designpattern.observer; import java.util.ArrayList; import java.util.List; public interface Match { List<Fans> fansList = new ArrayList<>();// 这一句 void addFans(Fans fans); void removeFans(Fans fans); void notifyResult(String result); }
package designpattern.observer; import java.util.ArrayList; import java.util.List; public class MatchOnTheSpot implements Match { // List<Fans> fansList = new ArrayList<>(); @Override public void addFans(Fans fans) { fansList.add(fans); } @Override public void removeFans(Fans fans) { fansList.remove(fans); } @Override public void notifyResult(String result) { for (Fans fans : fansList) { fans.react(result); } } }
package designpattern.observer; import java.util.ArrayList; import java.util.List; public class MatchOnTheTV implements Match { // List<Fans> fansList = new ArrayList<>(); @Override public void addFans(Fans fans) { fansList.add(fans); } @Override public void removeFans(Fans fans) { fansList.remove(fans); } @Override public void notifyResult(String result) { for (Fans fans : fansList) { fans.react(result); } } }
package designpattern.observer; public class Client { public static void main(String[] args) { HomeFans homeFans = new HomeFans(); AwayFans awayFans = new AwayFans(); // 现场看 Match match = new MatchOnTheSpot(); match.addFans(homeFans); match.addFans(awayFans); System.out.println("主场赢啦~"); match.notifyResult("win"); System.out.println("==========================="); // 电视上看 match = new MatchOnTheTV(); System.out.println("主场输啦~"); match.notifyResult("lose"); } }
主场赢啦~ 主场球迷:Yes! 我们赢啦,主场就是牛批!!! 客场球迷:输了,哎... =========================== 主场输啦~ 主场球迷:输了,哎... 客场球迷:Yes! 客场都赢啦,牛批!!!
总结:
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:设计模式 | 观察者模式/发布-订阅模式(observer/publish-subscribe) - Python技术站