Observer mode
Intention:
Defines a one-to-many dependency between objects, and when the state of an object changes, all objects that depend on it are notified and automatically updated.
Structure:
Advantages:
Abstract coupling between target (SUBJECT) and Observer (Observer)
Support for broadcast communications/notifications
Disadvantages:
can cause unexpected updates.
Example:
Consider such an example: Want to know the company's latest mm information? Join us mm Intelligence mail group. You only need to send us a subscription email, we will be the latest mm information to notify you in electronic form.
Now let's do it one step at a time. Obviously, the person who cares about the MM situation in the example is the Subscriber, and we use subscriber to express this category. Before defining subscriber, we first define a Mmstatus enumeration to represent the MM State:
1.enum mmstatus {dining, sleeping, Working};
Three constants are defined here to simply simulate the state of the MM. Now we can define the Subscriber class:
1.struct Subscriber
2.{
3. virtual void action (mmstatus status) = 0;
4. virtual ~subscriber () {}
5.};