码迷,mamicode.com
首页 > 编程语言 > 详细

设计模式 - 观察者模式 (C++实现)

时间:2019-07-23 11:31:33      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:not   alt   接收   sub   mes   ret   sdn   ffffff   text   

技术图片

#include <iostream>
#include <list>
#include <string>
using namespace std;
class ISubject;
class IObserver;
class Subject;
class Observer;


class ISubject {
private:
    list<IObserver*> observerList;
public:
    void AddObserver(IObserver *obs) {
        observerList.push_back(obs);
    };
    void RemoveObserver(IObserver *obs) {
        observerList.remove(obs);
    };
    virtual void Notified(IObserver *) = 0;

    void Update() {
        for (auto ob : observerList)
        {
            if (ob != NULL) {
                Notified(ob);
            }
        }
    }
};

class IObserver {
public:
    virtual void Received(ISubject *) = 0;
};

// 实例:发布者
class Subject :public ISubject
{
public:
    Subject() :ISubject() { };
    void Notified(IObserver *obs) {
        obs->Received(this);
    }
};

// 实例:接收(观察)者
class Observer :public IObserver
{
public:
    Observer(string& n) {
        name = n;
    };
    void Received(ISubject *sub) {
        cout << "this is " + name + " OBer, Received.\n";
    }
private:
    string name;
};

int main() {
    string val = "1";
    Observer *obs1 = new Observer(val);
    val = "2";
    Observer *obs2 = new Observer(val);
    val = "3";
    Observer *obs3 = new Observer(val);

    Subject *sub = new Subject();

    // 订阅消息
    sub->AddObserver(obs1);
    sub->AddObserver(obs2);
    sub->AddObserver(obs3);

    // 发布消息
    sub->Update();
    cout << "///////////////////////////////\n";
    sub->RemoveObserver(obs2);
    sub->Update();
    cout << "///////////////////////////////\n";

    /*
    this is 1 OBer, Received.
    this is 2 OBer, Received.
    this is 3 OBer, Received.
    ///////////////////////////////
    this is 1 OBer, Received.
    this is 3 OBer, Received.
    ///////////////////////////////
    */
    system("pause");
    return 0;
}

设计模式 - 观察者模式 (C++实现)

标签:not   alt   接收   sub   mes   ret   sdn   ffffff   text   

原文地址:https://www.cnblogs.com/ruoh3kou/p/11230572.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!