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

原文地址:https://www.cnblogs.com/mthoutai/p/7338314.html