定義了一種一對多的依賴關係,讓多個觀察者對象同時監聽某一個主題對象。這個主題對象在狀態發生變化時,會通知全部觀察者對象,使他們可以自動更新本身。java
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! 客場都贏啦,牛批!!!