观察者模式定义了一种一对多的依赖关系, 让多个观察对像同时监听某一个对象, 这个对象在改变时会通知所有观察者。
代码 1
在这个小例子中, 由间谍 spy 扮演被观察者窃取, 当间谍发现甲国家的秘密信息后它的状态改变, 然后通知扮演观察者的乙丙国, 乙丙国在收到 spy 的信息后会做出不一样的判断。
1public abstract class Country {
2 protected String countryName;
3 protected Spy007 spy;
4
5 public Country(String countryName, Spy007 spy) {
6 this.countryName = countryName;
7 this.spy = spy;
8 }
9
10 public abstract void update();
11}
1public class CountryA extends Country{
2
3 public CountryA(String countryName, Spy007 spy) {
4 super(countryName, spy);
5 }
6
7 /**
8 * 获取情报的方法
9 */
10 @Override
11 public void update() {
12 System.out.println(countryName+"得到情报: "+spy.getIntelligence()+" 决定与甲国开战!");
13 }
14}
1public class CountryB extends Country{
2
3 public CountryB(String countryName, Spy007 spy) {
4 super(countryName, spy);
5 }
6
7 /**
8 * 获取情报的方法
9 */
10 @Override
11 public void update() {
12 System.out.println(countryName+"得到情报: "+spy.getIntelligence()+" 决定与甲国建立关系!");
13 }
14}
1public class Spy {
2 private List<Country> countryList = new ArrayList<>();
3 private String intelligence;
4
5 /**
6 * 潜入国家
7 *
8 * @param country
9 */
10 public void attach(Country country) {
11 countryList.add(country);
12 }
13
14 /**
15 * 离开国家, 对country不发送变更提醒
16 * @param country
17 */
18 public void leave(Country country) {
19 countryList.remove(country);
20 }
21
22 /**
23 * 变更提醒
24 */
25 public void notifyCountry() {
26 for (Country c : countryList){
27 c.update();
28 }
29 }
30
31 /**
32 * 设置情报
33 * @param intelligence
34 */
35 public void setIntelligence(String intelligence) {
36 this.intelligence = intelligence;
37 }
38
39 /**
40 * 获取情报
41 * @return
42 */
43 public String getIntelligence() {
44 return intelligence;
45 }
46}
1public class Main {
2
3 public static void main(String[] args) {
4 Spy spy = new Spy();
5
6 //两个国家雇佣了007, 这两个国家是观察者
7 CountryA countryA = new CountryA("乙国", spy);
8 CountryB countryB = new CountryB("丙国", spy);
9
10 //间谍spy记下两个国家(记录通知对象)
11 spy.attach(countryA);
12 spy.attach(countryB);
13
14 //发现情报(间谍状态改变)
15 spy.setIntelligence("发现甲国研制了核武器!");
16
17 //向两个国家汇报(通知观察者)
18 spy.notifyCountry();
19 }
20}
21//输出
22乙国得到情报: 发现甲国研制了核武器! 决定与甲国开战!
23丙国得到情报: 发现甲国研制了核武器! 决定与甲国建立关系!