面试:C++观察者模式实现

 1 #include <list>
 2 
 3 class Subject;
 4 
 5 class Observer{
 6 public:
 7     virtual ~Observer(){};
 8     virtual void update(Subject * sub){};
 9 protected:
10     Observer(){};
11 
12 };
13 
14 class Subject {
15 public:
16     Subject() { };
17     virtual ~Subject() { };
18     virtual void attach(Observer* ob) {
19         this->_observers.push_back(ob);
20     }
21     void detach(Observer* ob) {
22         this->_observers.remove(ob);
23     }
24 
25     void notify(){
26         for(auto ob : _observers){
27             ob->update(this);
28         }
29     }
30 private:
31     std::list<Observer*> _observers;
32 };

 

posted @ 2017-08-06 17:20  wxquare  阅读(540)  评论(0编辑  收藏  举报