观察者模式 - 两国打仗靠间谍

 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         //两个国家雇佣了007
10         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     @Override
41     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     @Override
54     void Update() {
55         System.out.println(countryName+"得到情报:"+spy.getIntelligence()+"决定于甲国开战");
56     }
57     
58 }
59 //间谍007
60 class Spy007{
61     private ArrayList<Country> countrys = new ArrayList<Country>();
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 }

输出:

    乙国得到情报:甲国研制了核武器决定于甲国建交
    丙国得到情报:甲国研制了核武器决定于甲国开战

posted @ 2017-12-05 15:50  勤劳的杯子  阅读(149)  评论(0编辑  收藏  举报