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

C++设计模式之观察者模式

时间:2018-10-01 17:10:41      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:crete   notify   new   data   cts   com   sub   list   serve   

技术分享图片

//观察者模式
class Observer{
public:
    virtual void Updata() = 0;
};
class Subject{
public:
    void Attach(Observer* in){ m_list.push_back(in); }
    void Detach(Observer* out){ m_list.remove(out); }
    void Notify(){
        for (auto it = m_list.begin(); it != m_list.end(); it++){
            (*it)->Updata();
        }
    }
private:
    list<Observer*> m_list;
};
class ConcreteSubject :public Subject{
public:
    string SubjectState;
};
class ConcreteObserver:public Observer{
public:
    ConcreteObserver(ConcreteSubject *subject){
        m_subject = subject;
    }
    void Updata(){
        ObserverState = m_subject->SubjectState;
        cout << ObserverState << endl;
    }
private:
    ConcreteSubject *m_subject;
    string ObserverState;
};
int main(){
    ConcreteSubject *s = new ConcreteSubject();
    s->Attach(new ConcreteObserver(s));
    s->Attach(new ConcreteObserver(s));
    s->Attach(new ConcreteObserver(s));
    s->SubjectState = "ABC";
    s->Notify();
    return 0;
}

技术分享图片

C++设计模式之观察者模式

标签:crete   notify   new   data   cts   com   sub   list   serve   

原文地址:https://www.cnblogs.com/hustwx/p/9734913.html

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