添加观察者模式

master
a7458969 2019-12-22 01:25:09 +08:00
parent 5cdcb6c71e
commit 0ff74f30c7
2 changed files with 36 additions and 27 deletions

View File

@ -3,31 +3,40 @@
//
#include "Observer.h"
template<typename T>
int Observed<T>::AddObserver(Observer<T> *p) {
if(nullptr == p){
return -1;
}
int Observed::AddObserver(Observer *p) {
if(nullptr == p){
return -1;
}
for(std::vector<Observer*>::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<Observer*>::iterator itr = m_vObservers.begin();
for(typename std::vector<Observer<T>*>::iterator itr = m_vObservers.begin();
itr != m_vObservers.end();itr++){
if(((Observer*)*itr) == p){
if(((Observer<T>*)*itr) == p){
return 0;
}
}
this->m_vObservers.push_back(p);
return 0;
}
template<typename T>
int Observed<T>::DeleteObserver(Observer<T> *p) {
for(typename std::vector<Observer<T>*>::iterator itr = m_vObservers.begin();
itr != m_vObservers.end();itr++){
if(((Observer<T>*)*itr) == p){
return 0;
}
}
return 0;
}
int Observed::NoticeObserver() {
template<typename T>
int Observed<T>::NoticeObserver(T *p) {
if(nullptr == p){
return -1;
}
for(typename std::vector<Observer<T>*>::iterator itr = m_vObservers.begin();
itr != m_vObservers.end();itr++){
((Observer<T>*)*itr)->OnNotifyData(p);
}
return 0;
}

View File

@ -5,27 +5,27 @@
#ifndef GENERAL_OBSERVER_H
#define GENERAL_OBSERVER_H
#include <memory>
#include <vector>
class Observer;
template <typename T> class Observer;
template <typename T> class Observed{
public:
virtual ~Observed(){};
int AddObserver(Observer *); // 添加观察者
int DeleteObserver(Observer *); // 删除观察者
int NoticeObserver();
virtual int AddObserver(Observer <T>*); // 添加观察者
virtual int DeleteObserver(Observer <T>*); // 删除观察者
virtual int NoticeObserver(T *);
protected:
std::vector<Observer*> m_vObservers;
std::vector<Observer <T>*> m_vObservers;
};
class Observer
template <typename T>class Observer
{
public:
void OnNotifyData();
virtual void OnNotifyData(T* ){};
private:
};
#endif //GENERAL_OBSERVER_H