• c++ 观察者模式(observer)


    观察者模式:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。它还有两个别名,依赖 (Dependents),发布-订阅(Publish-Subsrcibe)。可以举个博客订阅的例子,当博主发表新文章的时候,即博主状态发生了改 变,那些订阅的读者就会收到通知,然后进行相应的动作,比如去看文章,或者收藏起来。博主与读者之间存在种一对多的依赖关系。下面给出相应的UML图设 计。

    以博客和博客的粉丝(observer)为例

    #include <iostream>
    #include <list>
    #include <string>
    
    using namespace std;
    
    class Observer
    {
    public:
        Observer() {}
        virtual ~Observer() {}
        virtual void Update() {}
    
    };
    
    class Blog
    {
    public:
        Blog(){}
        virtual ~Blog() {}
        void Attach(Observer *observer)
        {
            m_observers.push_back(observer);
        }
        void Remove(Observer* observer)
        {
            m_observers.remove(observer);
        }
        void Notify()
        {
            list<Observer*>::iterator iter = m_observers.begin();
            for(;iter != m_observers.end(); iter++)
                (*iter)->Update();
        }
        virtual void SetStatus(string s)
        {
            m_status = s;
        }
        virtual std::string GetStatus()
        {
            return m_status;
        }
    private:
        list<Observer* > m_observers;
    protected:
        std::string m_status;
    };
    
    class BlogBKY : public Blog
    {
    public:
        BlogBKY(string name):m_name(name) {}
        ~BlogBKY() {}
        void SetStatus(string s)
        {
            m_status = s ;
        }
        string GetStatus()
        {
            return m_status;
        }
    private:
        string m_name;
    };
    
    class ObserverBlog : public Observer
    {
    public:
        ObserverBlog(string name,Blog *blog):m_name(name),m_blog(blog)
        {
        
        }
        ~ObserverBlog() {}
        void Update()
        {
            std::string status = m_blog->GetStatus();
            cout << m_name  <<"-------" << status <<endl;
        }
    private:
        std::string m_name;
        Blog *m_blog;
    };

    接口的使用:

    #include "observer.h"
    int main()
    {
        Blog *blog = new BlogBKY("onlycxue");
        Observer *observer1 = new ObserverBlog("hello",blog);
        blog->Attach(observer1);
        blog->SetStatus("发表博客!");
        blog->Notify();
        system("pause");
        //delete blog;
        //delete observer1;
        return 0;
  • 相关阅读:
    iOS 字体
    接口继承和实现继承的区别
    实验楼实验——LINUX基础入门
    试看看能不能发布
    mysql binlog恢复
    percona
    ssh2 php扩展
    sphinx
    ngios
    socketlog
  • 原文地址:https://www.cnblogs.com/onlycxue/p/3492547.html
Copyright © 2020-2023  润新知