generallib/obj/inc/Observer.h

67 lines
1.5 KiB
C
Raw Normal View History

2019-12-21 10:50:15 +00:00
//
// Created by 29019 on 2019/12/21.
//
#ifndef GENERAL_OBSERVER_H
#define GENERAL_OBSERVER_H
2019-12-22 04:01:49 +00:00
#include <memory>
#include <vector>
2019-12-21 10:50:15 +00:00
2019-12-22 04:01:49 +00:00
template <typename T> class Observer;
2019-12-21 10:50:15 +00:00
2019-12-22 04:01:49 +00:00
template <typename T> class Observed{
public:
virtual ~Observed(){};
virtual int AddObserver(Observer <T>*); // 添加观察者
virtual int DeleteObserver(Observer <T>*); // 删除观察者
virtual int NoticeObserver(T *);
protected:
std::vector<Observer <T>*> m_vObservers;
2019-12-21 10:50:15 +00:00
};
2019-12-22 04:01:49 +00:00
template <typename T>class Observer
{
public:
virtual void OnNotifyData(T* ){};
private:
2019-12-21 10:50:15 +00:00
2019-12-22 04:01:49 +00:00
};
template<typename T>
int Observed<T>::AddObserver(Observer<T> *p) {
if(nullptr == p){
return -1;
}
for(typename std::vector<Observer<T>*>::iterator itr = m_vObservers.begin();
itr != m_vObservers.end();itr++){
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;
}
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;
}
2019-12-21 10:50:15 +00:00
#endif //GENERAL_OBSERVER_H