zoukankan      html  css  js  c++  java
  • 观察者模式(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;
    }
  • 相关阅读:
    Gym
    UVALive
    UVALive
    UVALive
    UVALive
    Codeforces Round #367 (Div. 2) D. Vasiliy's Multiset Trie
    HDU 5816 Hearthstone 概率dp
    欧几里德与扩展欧几里德算法(转)
    差分约束系统详解(转)
    2016年第七届蓝桥杯C/C++程序设计本科B组决赛
  • 原文地址:https://www.cnblogs.com/tiandsp/p/2568834.html
Copyright © 2011-2022 走看看