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 (江东敏)

你可能感兴趣的:(Observer Design Pattern)