zoukankan      html  css  js  c++  java
  • 观察者模式——三英雄战吕布

    观察者模式:

    被观察者:吕布

    观察者:张飞,关羽,刘备

    #include <iostream>
    #include <vector>
    #include <list>
    using namespace std;

    class SubjectPeople;
    class ObserverPeople
    {
    public:
    virtual void Action()=0;
    };

    class SubjectPeople
    {
    public:
    virtual void RegisterPeople(ObserverPeople* ob) = 0;
    virtual void RemovePeople(ObserverPeople* ob) = 0;
    virtual void NotifyPeople() = 0;
    };

    class LvBuSubject:public SubjectPeople
    {
    protected:
    list<ObserverPeople *> OP;

    public:
    void RegisterPeople(ObserverPeople* ob)
    {
    OP.push_back(ob);
    }

    void RemovePeople(ObserverPeople* ob)
    {
    list<ObserverPeople*>::iterator it = OP.begin();
    while (it!=OP.end())
    {
    if (*it==ob)
    {
    OP.remove(*it);
    return ;
    }
    it++;
    }
    }

    void NotifyPeople()
    {
    list<ObserverPeople*>::iterator it = OP.begin();
    while (it!=OP.end())
    {
    (*it)->Action();
    it++;
    }
    }

    };


    class GuanYuOberver:public ObserverPeople
    {
    public:
    GuanYuOberver(SubjectPeople*op):sp(*op)
    {
    sp.RegisterPeople(this);
    }

    public:
    void Action()
    {
    cout<<"关羽给吕布一刀"<<endl;
    }

    protected:
    SubjectPeople& sp;
    };

    class ZhangFeiOberver:public ObserverPeople
    {
    public:
    ZhangFeiOberver(SubjectPeople*op):sp(*op)
    {
    sp.RegisterPeople(this);
    }

    public:
    void Action()
    {
    cout<<"张飞给吕布一杖"<<endl;
    }

    protected:
    SubjectPeople& sp;
    };

    class LiuBeiOberver:public ObserverPeople
    {
    public:
    LiuBeiOberver(SubjectPeople*p):sp(*p)
    {
    sp.RegisterPeople(this);
    }

    public:
    void Action()
    {
    cout<<"刘备给吕布一刀"<<endl;
    }

    protected:
    SubjectPeople& sp;
    };



    int main()
    {
    LvBuSubject lvb;
    GuanYuOberver gy(&lvb);
    LiuBeiOberver liub(&lvb);
    ZhangFeiOberver zf(&lvb);

    lvb.NotifyPeople();
    return 0;
    }



  • 相关阅读:
    The 9th SWJTU ACM Final Tutorial
    The 9th SWJTU ACM Online Tutorial
    ACdream群赛(5) D Palindrome
    ACdream群赛(5)总结
    The 9th SWJTU ACM Qualification Tutorial
    IIUC Inter University Programming Contest 2012总结
    曾经流行的,即将流行的几种渲染模式(render pipeline)
    ogre线程及其死锁问题
    crysis shader系统简单分析
    编译并集成mono 2.6.4到应用程序中
  • 原文地址:https://www.cnblogs.com/BreakMind/p/2299162.html
Copyright © 2011-2022 走看看