Observer mode (C ++)

Source: Internet
Author: User
#include <iostream>#include <string>#include <vector>#include <algorithm>#include <functional>using namespace std;class Observer{public:    Observer(){}    virtual ~Observer(){}    virtual void run()=0;protected:    string _name;};class atlete : public Observer{public:    atlete(string name){_name=name;}    virtual ~atlete(){}    void run()    {        cout<<"atlete "<<_name<<" run"<<endl;    }};class Subject{public:    Subject(){}    virtual void notify()=0;    virtual void attach(Observer*)=0;    virtual void detach(Observer*)=0;protected:    vector<Observer*> vec;};class referee : public Subject{public:    referee(){}    virtual ~referee(){}    void attach(Observer* p)    {        vec.push_back(p);    }    void detach(Observer* p)    {        vec.erase(remove_if(vec.begin(),vec.end(),bind1st(equal_to<Observer*>(),p)));    }    void notify()    {        cout<<"referee say 'run'"<<endl;        vector<Observer*>::iterator it;        for (it=vec.begin();it!=vec.end();it++)        {            (*it)->run();        }    }};int main(){    Observer *pat1=new atlete("zhangsan");    Observer *pat2=new atlete("lisi");    Observer *pat3=new atlete("wangwu");    Subject *pre=new referee;    pre->attach(pat1);    pre->attach(pat2);    pre->attach(pat3);    pre->notify();        cout<<endl;    pre->detach(pat2);    pre->notify();    delete pat1;    delete pat2;    delete pat3;    delete pre;    system("pause");    return 0;}

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.