ecklist is : <" + this._checkList + ">.");
}
public String toString() {
return "Assignee";
}
}
public class Reviewer extends TaskObserver {
@Override
public void sendEmail() {
print("[Reviewer] The current status is : <" + this._status + ">.");
print("[Reviewer] The current process is : <" + this._process + ">.");
print("[Reviewer] The current checklist is : <" + this._checkList + ">.");
}
public String toString() {
return "Reviewer";
}
}
public class Reporter extends TaskObserver {
@Override
public void sendEmail() {
print("[Reporter] The current status is : <" + this._status + ">.");
print("[Reporter] The current process is : <" + this._process + ">.");
print("[Reporter] The current checklist is : <" + this._checkList + ">.");
}
public String toString() {
return "Reporter";
}
}
Java设计模式 - 观察者模式(4)
时间:2011-01-17 GooooWei
然后我们需要编写一个类用来演示观察者模式,在这个类中会演示注册观察者,取消特定观察者,更改主体对象信息然后观察者自动得到通知并更新信息。
public class TaskManager {
public static void main(String[] args) {
// Create subject
TaskSubject taskSubject = new TaskSubject();
// Create observers
IObserver assignee = new Assignee();
IObserver reviewer = new Reviewer();
IObserver reporter = new Reporter();
// 注册观察者[因为我们使用的是一个列表,所以在通知观察者的时候是按照添加的顺序通知的]
taskSubject.registerObserver(assignee);
taskSubject.registerObserver(reviewer);
taskSubject.registerObserver(reporter);
// 更新主体对象的信息
taskSubject.setStatus("Assigned");
taskSubject.setProcess("No Process Attacted");
taskSubject.setCheckList("CheckList Version 1.0");
// 通知所有观察者
taskSubject.notifyObserver();
// 更新主体对象信息
taskSubject.setStatus("In Progress");
taskSubject.setProcess("Process Attached");
taskSubject.setCheckList("CheckList Version Final Version");
// 取消报告者的注册,并通知剩余所有观察者
taskSubject.removeObserver(reporter);
taskSubject.notifyObserver();
}
}
输出的信息如下:
< Assignee > is registed successfully!
< Reviewer > is registed successfully!
< Reporter > is registed successfully!
[Assignee] The current status is : &l
|