Observer Design Pattern

Copyright @ Joel Jiang(江东敏) at 2017.09.16 00:00 a.m
in Shenzhen.China. LIST- TE- E33 -02

1.Intent:
.The observer pattern is a software design pattern in which an object, called the subject,maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.It is often used in "event driven" software skeleton such as the "document and view" in windows MFC application".
.Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.Whenever the Subject changes, it broadcasts to all registered Observers that it has changed, and each Observer queries the Subject for that subset of the Subject's state that it is responsible for monitoring.
2.Structure:

image.png

3.Observer and Mediator pattern:
They are competing patterns. The difference between them is that Observer distributes communication by introducing "observer" and "subject" objects, whereas a Mediator object encapsulates the communication between other objects. We've found it easier to make reusable Observers and Subjects than to make reusable Mediators.

4.The code example:
The class of subject :

Paste_Image.png

The notify function accomplish method:
Paste_Image.png

The class of obsever :
Paste_Image.png

The subclass functions are defined as follow:
Paste_Image.png

The sharing of knowledge, the spirit of encouragement.
By Joel Jiang (江东敏)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容