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

  • 相关阅读:
    Chrome 开发者工具使用技巧
    POJ2485 Highways 【MST】
    Android 之UI自适应解决方式
    自己封装的轮播工具
    usb芯片调试经验
    SQLSEVER 中的那些键和约束
    mysql通过DATE_FORMAT将错误数据恢复
    vim使用(二):经常使用功能
    Linux系列-Xshell连接本地VMware安装的Linux虚拟机
    LeetCode 107 Binary Tree Level Order Traversal II(二叉树的层级顺序遍历2)(*)
  • 原文地址:https://www.cnblogs.com/mthoutai/p/7338314.html
Copyright © 2020-2023  润新知