观察者设计模式及java Demo

观察者设计模式

1、主题对象管理着某些数据;
2、当主题内的数据改变就会通知观察者(一旦数据发生改变,新的数据会以某种形式送到观察者手上);
3、观察者已经订阅(注册)主题以便在主题数据改变时能够收到更新;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**   
* @Title: ObserverTest.java
* @Package com.primeton.test
* @Description: TODO(用一句话描述该文件做什么)
* @date 2015年11月6日 下午11:04:07
* @version V1.0
*/
package com.primeton.test;
import java.util.Observable;
import java.util.Observer;
/**
* @ClassName: ObserverTest
* @Description: TODO(这里用一句话描述这个类的作用)
* @author yuechang
* @date 2015年11月6日 下午11:04:07
*/
public class Test {
public static void main(String[] args) {
School school = new School("娄底师专");
Student studentA = new Student(school.getSchoolName(), "A");
Student studentB = new Student(school.getSchoolName(), "B");

school.addObserver(studentA);
school.addObserver(studentB);

System.out.println(school);
System.out.println(studentA);
System.out.println(studentB);

// 学校改名了
school.setSchoolName("湖南人文科技学院");
school.setChanged();
school.notifyObservers(school);

System.out.println(school);
System.out.println(studentA);
System.out.println(studentB);
}
}

class School extends Observable {

private String schoolName;
public School() {
}
/**
* @param schoolName
*/
public School(String schoolName) {
super();
this.schoolName = schoolName;
}
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
@Override
public String toString() {
return "School [schoolName=" + schoolName + "]";
}
@Override
protected synchronized void setChanged() {
super.setChanged();
}
}

class Student implements Observer {

private String studentName;
private String schoolName;
public Student() {
}

/**
* @param studentName
* @param schoolName
*/
public Student(String schoolName, String studentName) {
super();
this.studentName = studentName;
this.schoolName = schoolName;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
@Override
public void update(Observable o, Object arg) {

if (arg instanceof School) {
this.schoolName = ((School) arg).getSchoolName();
}
}
@Override
public String toString() {
return "Student [studentName=" + studentName + ", schoolName=" + schoolName + "]";
}
}