C + + Implementation Viewer (Observer) mode

Source: Internet
Author: User

Observer (Observer) mode, is one of the common patterns. A newspaper, for example, has a lot of subscribers. The subscriber did not know when the newspaper would come, he only knew he had subscribed to the newspaper. Subscribers are here to act as observers, while newspapers are observers. once the newspaper is printed, it should be delivered to subscribers in time, and if the newspaper is regarded as an object, the newspaper is the link between the Observer (Subscriber) and the Observer (newspaper). The observer needs to maintain a newspaper-related variable or function, in which case the variable is whether the Subscriber receives the newspaper, can be set to a Boolean, and when received, the Subscriber needs to update the variable.

Here is the source code:
"Observer.H" #ifndef _observer_h_#define _observer_h_#include <list>using namespace Std;class observer;/* The Observer Interface */class Subject{public:subject (): m_issue (0) {} void Attach (Observer *oo);//subscribe to this object void Detach (Obser ver *oo);//Cancel subscription void Notify ();//notify Subscribers to update void virtual Issue () = 0;//release function bool Getissue () {return m_issu    E        } ~subject () {list<observer*>::iterator iter1,iter2,temp;        for (Iter1 = M_observerlist.begin (), iter2 = M_observerlist.end ();        Iter1! = Iter2;            ) {temp = Iter1;            ++iter1;        M_observerlist.erase (temp);    } m_observerlist.clear (); }protected:bool m_issue;//Release flag list<observer*> m_observerlist;//subscriber Queue};/* Watcher interface */class Observer{public:obs    Erver (): m_receive (0) {}; void virtual Update ()//update function {} void virtual showmessage () = 0;//simulates the function associated with the Observer Protected:bool m_receive;//receive the newspaper label */class Concretesubject:public, a specific observer of};/*Subject{public:concretesubject () {} void Issue ();    };/* specific observer */class subscriber1:public observer{public:void Virtual Update (); void ShowMessage ();};    Class Subscriber2:public observer{public:void virtual Update (); void ShowMessage ();}; #endif

The Observer Interface Description:
1. The subscription object, the unsubscribe, the notification update function, is the common behavior of all the observers, so it is abstracted out as the interface of the Observer.
2. The release function simulates changing state functions, because different observers have different ways, so declare them as pure virtual functions, implemented in derived classes.
3. The observer is implemented with the list template in Std, so a destructor is required to release it.
Viewer Interface Description:
1. Because all observers have an update status, declare it as an interface.
The 2.Update () function has different behavior for different concrete objects, so it is implemented in derived classes and declared as pure virtual functions.
The 3.ShowMessage () function is used to simulate an action that is related to the observer, and if the observer state changes, the observer needs to perform some action, which is achieved here. This example is used to display the information received in a newspaper.

Here is the implementation part of the class: Observer.cpp

#include "Observer.H" #include <algorithm> #include <iostream>/* subscribe to newspaper */void Subject::attach (Observer *oo) { M_observerlist.push_back (OO);}    /* Unsubscribe */void Subject::D etach (Observer *oo) {list<observer*>::iterator iter;    iter = Std::find (M_observerlist.begin (), M_observerlist.end (), OO);    while (iter! = M_observerlist.end ()) {m_observerlist.erase (ITER);    }}/* Notification update */void subject::notify () {list<observer*>::iterator iter=m_observerlist.begin ();    for (; ITER! = M_observerlist.end (); iter++) {(*iter)->update ();    }}/* Change Status */void concretesubject::issue () {this->m_issue =!this->m_issue;        if (this->m_issue) {cout << "Magazine is issued!\n";        This->notify ();    This->m_issue = false;    }}/* Subscriber update */void subscriber1::update () {this->m_receive = true;    This->showmessage (); This->m_receive = false;} void Subscriber1::showmessage () {cout << "Subscriber1 has receIved the newspapers!\n ";}    /* Subscriber update */void subscriber2::update () {this->m_receive = true;    This->showmessage (); This->m_receive = false;} void Subscriber2::showmessage () {cout << "Subscriber2 has received the newspapers!\n";}


Here is the main program section:
#include "Observer.H" #include <iostream>int main () {    Subject *sub=new ConcreteSubject ();//Observed    by Observer *customer1 = new Subscriber1 ();//Observer 1    Observer *customer2 = new Subscriber2 ();//Observer 2    Sub->attach ( CUSTOMER1);//viewer 1 subscribe to newspaper    Sub->attach (customer2);//Viewer 2 subscribe to newspaper        if (Sub->getissue ())    {        cout < < "newspapers has issued!\n";    }    else    {        cout << "Newspapers have not issued!\n";    }    Sub->issue ();       Issue newspaper    cout<<endl;    if (Sub->getissue ())    {        cout << "Newspapers has issued!\n";    }    else    {        cout << "Newspapers have not issued!\n";    }    Sub->detach (customer1);//viewer 1 Unsubscribe    sub->issue ();        Issue newspaper    return 0;}




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

C + + Implementation Viewer (Observer) mode

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.