The observer pattern of design pattern and its C + + general implementation (i)

Source: Internet
Author: User

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.};

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.