From 0ff74f30c74a5fe25bf04c04fd0fd31014666e93 Mon Sep 17 00:00:00 2001 From: a7458969 <290198252@qq.com> Date: Sun, 22 Dec 2019 01:25:09 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=A7=82=E5=AF=9F=E8=80=85?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/pattern/Observer.cpp | 47 ++++++++++++++++++++++++---------------- src/pattern/Observer.h | 16 +++++++------- 2 files changed, 36 insertions(+), 27 deletions(-) diff --git a/src/pattern/Observer.cpp b/src/pattern/Observer.cpp index 679991e..2c076ea 100644 --- a/src/pattern/Observer.cpp +++ b/src/pattern/Observer.cpp @@ -3,31 +3,40 @@ // #include "Observer.h" +template +int Observed::AddObserver(Observer *p) { + if(nullptr == p){ + return -1; + } - -int Observed::AddObserver(Observer *p) { - if(nullptr == p){ - return -1; - } - for(std::vector::iterator itr = m_vObservers.begin(); - itr != m_vObservers.end();itr++){ - if(((Observer*)*itr) == p){ - return 0; - } - } - this->m_vObservers.push_back(p); -} - -int Observed::DeleteObserver(Observer *p) { - for(std::vector::iterator itr = m_vObservers.begin(); + for(typename std::vector*>::iterator itr = m_vObservers.begin(); itr != m_vObservers.end();itr++){ - if(((Observer*)*itr) == p){ + if(((Observer*)*itr) == p){ + return 0; + } + } + this->m_vObservers.push_back(p); + return 0; +} +template +int Observed::DeleteObserver(Observer *p) { + for(typename std::vector*>::iterator itr = m_vObservers.begin(); + itr != m_vObservers.end();itr++){ + if(((Observer*)*itr) == p){ return 0; } } return 0; } - -int Observed::NoticeObserver() { +template +int Observed::NoticeObserver(T *p) { + if(nullptr == p){ + return -1; + } + for(typename std::vector*>::iterator itr = m_vObservers.begin(); + itr != m_vObservers.end();itr++){ + ((Observer*)*itr)->OnNotifyData(p); + } return 0; } + diff --git a/src/pattern/Observer.h b/src/pattern/Observer.h index ce01af8..f30cd54 100644 --- a/src/pattern/Observer.h +++ b/src/pattern/Observer.h @@ -5,27 +5,27 @@ #ifndef GENERAL_OBSERVER_H #define GENERAL_OBSERVER_H - #include #include -class Observer; +template class Observer; template class Observed{ public: virtual ~Observed(){}; - int AddObserver(Observer *); // 添加观察者 - int DeleteObserver(Observer *); // 删除观察者 - int NoticeObserver(); + virtual int AddObserver(Observer *); // 添加观察者 + virtual int DeleteObserver(Observer *); // 删除观察者 + virtual int NoticeObserver(T *); protected: - std::vector m_vObservers; + std::vector*> m_vObservers; }; -class Observer +template class Observer { public: - void OnNotifyData(); + virtual void OnNotifyData(T* ){}; private: }; + #endif //GENERAL_OBSERVER_H