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;
    }



  • 相关阅读:
    Codeforces Round #594 (Div. 2) ABC题
    Codeforces Round #596 (Div. 2) ABCD题
    数据结构实验5——二叉树
    数据结构实验4——字符串匹配
    数据结构实验3——用栈求解算术表达式
    友链
    Codeforces Round #577 (Div. 2)
    Educational Codeforces Round 70 (Rated for Div. 2)
    Codeforces Round #578 (Div. 2)
    2020 Multi-University Training Contest 10(待补
  • 原文地址:https://www.cnblogs.com/BreakMind/p/2299162.html
Copyright © 2011-2022 走看看