c++实现观察者模式

1、构建被观察者基类

class IObserver
{
    public:
        virtual void ReceiveMsg(std::string msg) = 0;

    private:

};

2、构建被观察者1

class Student: public IObserver
{
    public:

        void ReceiveMsg(std::string msg) override {
            std::cout <<"学生知道了,终于"<<msg<< std::endl;
        }
    private:

};

3、构建被观察者2

class Teacher :public IObserver
{
    public:

        void ReceiveMsg(std::string msg) override {
            std::cout << "老师知道了,终于" << msg << std::endl;
        }
    private:

};

4、构建观察者(消息管理者)

class  Radio
{
    private:
        std::vector<IObserver *> m_Listener;

    public:

        void Register(IObserver * observer) {
            m_Listener.push_back(observer);
        }

        void UnRegister(IObserver* observer) {
            auto it = std::find(m_Listener.begin(), m_Listener.end(), observer);
            if (it != m_Listener.end()) {
                m_Listener.erase(it);
            }
        }


        void Broadcast(std::string msg) {
        
            if (m_Listener.size() == 0)
                return;

            for ( auto listener: m_Listener){
                listener->ReceiveMsg(msg);
            }
        }

    private:

};

5、调用

int main()
{
    auto ob1 = new Student();
    auto ob2 = new Teacher();

    auto audio = new Radio();
    audio->Register(ob1);
    audio->Register(ob2);
      
    audio->Broadcast("今天放暑假!");
         
    delete audio;
    delete ob1;
    delete ob2;
}

6、结果

 

posted @ 2023-06-30 11:40  卖雨伞的小男孩  阅读(111)  评论(0编辑  收藏  举报