• 观察者模式(C++)


    #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;
    }
  • 相关阅读:
    众多linux 库及工具意思的解释
    ubuntu root 登录
    Oscillator的参数解释
    世界观和方法论写给学弟学妹的
    元件的降额使用可靠度设计
    电子元件又一话——电感篇
    【转】什么是磁珠(Ferrite Bead 即 FB)
    Digital System Design Guidelines
    几种典型接口的电平标准
    珀耳帖效应
  • 原文地址:https://www.cnblogs.com/tiandsp/p/2568834.html
Copyright © 2020-2023  润新知