The Observer pattern defines a One-to-many object relationship: A Principal object corresponds to multiple observer objects. When the Subject object changes, all its corresponding observer objects are automatically notified and updated.
This article will give a corresponding example of how the observer pattern is working. This example demonstrates a case where all the people involved in the task are notified when the information about a task changes. The task information includes the status of the task, the processing process used by the task, and the checklist[of the task to ensure that the task completes all scheduled functional lists and avoids some common errors.
Two interfaces are defined first: The Principal object interface and the Observer object interface.
/** *//**
* 主体对象接口定义了注册观察者,取消观察者和通知观察者方法。
*
*/
public interface ISubject {
/** *//**
* 为该主体对象注册一个观察者。
*/
public void registerObserver(IObserver observer);
/** *//**
* 从该主体对象中取消一个观察者的注册。
*/
public void removeObserver(IObserver observer);
/** *//**
* 通知所有观察者。
*/
public void notifyObserver();
}
/** *//**
* 观察者接口简单定义了一个用来更新观察者信息的接口。
* 当主体对象被更新时,这个接口方法会被自动调用并更新信息。
*/
public interface IObserver {
/** *//**
* 接口方法用来更新观察者的信息。
*/
public void remind(ITask taskSubject);
}
These two interfaces define only the interfaces required by the subject object and the Observer object, but do not implement specific methods and interfaces for any task-related. The following defines a task interface to specify what functions the task should have. The advantage of such a separate definition is that if we break down different modules, if one party needs to be updated, the other side will not be affected.
/** *//**
* 这里定义了一个任务应该具有的功能。
*/
public interface ITask {
public void setStatus(String status);
public String getStatus();
public void setProcess(String process);
public String getProcess();
public void setCheckList(String checkList);
public String getCheckList();
}