zoukankan      html  css  js  c++  java
  • Observer观察者模式

    #include <iostream>
    #include <string.h>
    #include <vector>
    using namespace std;
    //观察者模式。
    //定义了一对多的关系,让多个观察对象同一时候监听一个主题对象,
    //当主题对象发生变化时,多个对象作出对应的响应。
    class School
    {
    public:
        School(char *s)
        {
            str = new char[strlen(s)];
            strcpy(str,s);
        }
        char *GetState()
        {
            return str;
        }
        virtual void Say() = 0;
    private:
        char *str;
    };
    class Student1 : public School
    {
    public:
        Student1(char *str) :School(str){}
        void Say()
        {
            cout <<GetState()<<"!Student1别玩手机了。" << endl;
        }
    private:
    };
    class Student2 : public School
    {
    public:
        Student2(char *str) :School(str){}
        void Say()
        {
            cout <<GetState()<< "!Student2别玩游戏了" << endl;
        }
    private:
    };
    
    class SayerBase
    {
    public:
        virtual void AddMember(School *sl) = 0;
        virtual void Shout() = 0;
        virtual void Remove(School *sl) = 0;
    protected:
        vector<School *> vtr;
    };
    class Sayer1 : public SayerBase
    {
    public:
        void AddMember(School *sl)
        {
            vtr.push_back(sl);
        }
        void Shout()
        {
            vector<School *>::iterator it;
            it = vtr.begin();
            while (it != vtr.end())
            {
                (*it)->Say();
                it++;
            }   
        }
        void Remove(School *sl)
        {
            vector<School*> ::iterator it = vtr.begin();
            while (it != vtr.end())
            {
                if (*it == sl)
                {
                    vtr.erase(it);
                    return;
                }
            }
        }
    private:
    };
    int main()
    {
        SayerBase *sb = new Sayer1();//创建一个通知对象。

    School *s1 = new Student1("老师来了"); School *s2 = new Student2("老师来了"); sb->AddMember(s1); sb->AddMember(s2); sb->Shout(); sb->Remove(s1); sb->Shout(); return 0; }

  • 相关阅读:
    python之openpyxl模块(最全总结 足够初次使用)
    随笔 遇见
    浅析企业服务器安全防护的七个切入点
    jQuery.API源码深入剖析以及应用实现(1) - 核心函数篇
    常用Javascript精选(二)
    随笔 生活与生命
    jquery插件 8个很有用的jQuery插件
    jquery插件 5个小插件
    常用Javascript精选(一)
    jQuery库与其他JS库冲突的解决办法(转)
  • 原文地址:https://www.cnblogs.com/mthoutai/p/7338314.html
Copyright © 2011-2022 走看看