1 import java.util.ArrayList; 2 3 //观察者模式 4 public class Observer { 5 6 public static void main(String[] args) { 7 //间谍007 8 Spy007 spy007 = new Spy007(); 9 //两个国家雇佣了00710 Country coutryA = new CuntryA("乙国",spy007);11 Country coutryB = new CuntryB("丙国",spy007);12 //007记住了两个国家13 spy007.Attach(coutryA);14 spy007.Attach(coutryB);15 //007发现了情报16 spy007.setIntelligence("甲国研制了核武器");17 //向两个国家汇报情况18 spy007.Notify();19 }20 }21 //抽象国家类22 abstract class Country{23 protected String countryName;24 protected Spy007 spy;25 //构造函数26 public Country(String countryName, Spy007 spy) {27 this.countryName = countryName;28 this.spy = spy;29 }30 //获取情报的抽象方法31 abstract void Update();32 }33 //具体的A类国家34 class CuntryA extends Country{35 36 public CuntryA(String countryName,Spy007 spy) {37 super(countryName, spy);38 }39 //获取情报的方法40 @Override41 void Update() {42 System.out.println(countryName+"得到情报:"+spy.getIntelligence()+"决定于甲国建交");43 44 }45 46 }47 //具体的B类国家48 class CuntryB extends Country{49 public CuntryB(String countryName,Spy007 spy) {50 super(countryName,spy);51 }52 53 @Override54 void Update() {55 System.out.println(countryName+"得到情报:"+spy.getIntelligence()+"决定于甲国开战");56 }57 58 }59 //间谍00760 class Spy007{61 private ArrayListcountrys = new ArrayList ();62 //具体的情报63 private String intelligence;64 //进入国家65 public void Attach(Country country) {66 countrys.add(country);67 }68 //离开国家69 public void Detach(Country country) {70 countrys.remove(country);71 }72 //通知情报73 public void Notify() {74 for(Country c : countrys) {75 c.Update();76 }77 }78 //设定情报79 public void setIntelligence(String intelligence) {80 this.intelligence = intelligence;81 }82 //获取情报83 public String getIntelligence() {84 return intelligence;85 }86 }
输出:
乙国得到情报:甲国研制了核武器决定于甲国建交
丙国得到情报:甲国研制了核武器决定于甲国开战