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

    观察者模式

    定义

    定义对象间的⼀种⼀对多(变化)的依赖关系,以便当⼀个对象(Subject)的状态发⽣改变时,所有 依赖于它的对象都得到通知并⾃动更新。 ——《 设计模式》 GoF

    背景

    ⽓象站发布⽓象资料给数据中⼼,数据中⼼经过处理,将⽓象信息更新到两个不同的显示终端(A 和B);

    要点

    观察者模式使得我们可以独⽴地改变⽬标与观察者,从⽽使⼆者之间的关系松耦合;

    观察者⾃⼰决定是否订阅通知,⽬标对象并不关注谁订阅了;

    观察者不要依赖通知顺序,⽬标对象也不知道通知顺序;

    常使⽤在基于事件的ui框架中,也是MVC的组成部分;

    常使⽤在分布式系统中,actor框架中;

    本质

    触发联动

    伪代码实现

    #include <vector>
    
    class IDisplay {
    public:
        virtual void Show(float temperature) = 0;
        virtual ~IDisplay() {}
    };
    
    class DisplayA : public IDisplay {
    public:
        virtual void Show(float temperature);
    };
    
    class DisplayB : public IDisplay{
    public:
        virtual void Show(float temperature);
    };
    
    class WeatherData {
    };
    
    class DataCenter {
    public:
        void Attach(IDisplay * ob);
        void Detach(IDisplay * ob);
        void Notify() {
            float temper = CalcTemperature();
            for (auto iter = obs.begin(); iter != obs.end(); iter++) {
                (*iter)->Show(temper);
            }
        }
    
    private:
        virtual WeatherData * GetWeatherData();
    
        virtual float CalcTemperature() {
            WeatherData * data = GetWeatherData();
            // ...
            float temper/* = */;
            return temper;
        }
        std::vector<IDisplay*> obs;
    };
    
    int main() {
        DataCenter *center = new DataCenter;
        IDisplay *da = new DisplayA();
        IDisplay *db = new DisplayB();
        center->Attach(da);
        center->Attach(db);
        center->Notify();
        
        //-----
        center->Detach(db);
        center->Notify();
        return 0;
    }
  • 相关阅读:
    cobbler自动安装系统(Centos7.X)
    企业级全网服务监控
    javascript中的getElementById、getElementsByName、getElementByTagName详解
    JavaScript中Math对象
    网络编程这结构体发送
    vue中'. native'修饰符的使用
    vue中render: h => h(App)的详细解释
    关于内存对齐的几点记忆
    _initialize() 与__construct()的区别
    PHP的 __DIR__ 作用
  • 原文地址:https://www.cnblogs.com/boluo007/p/15732208.html
Copyright © 2011-2022 走看看