#include <cstdlib>
#include <iostream>
#include <list>
#include <algorithm>
#include <string>
using namespace std;
template<class T>
class Observer
{
protected:
T m_Value;
public:
Observer(T t):m_Value(t){}
virtual ~Observer(){cout<<"析构基类Observer"<<endl;}
virtual void Draw() = 0;
virtual void Update(T n){m_Value = n;Draw();}
};
template<class T>
class ObserverZhu:public Observer<T>
{
public:
ObserverZhu(T t):Observer<T>(t){}
virtual ~ObserverZhu(){cout<<"析构子类ObserverZhu"<<endl;}
virtual void Draw(){cout<<"画一个值为:"<<Observer<T>::m_Value<<" 的柱状图"<<endl;}
};
template<class T>
class ObserverBing:public Observer<T>
{
public:
ObserverBing(T t):Observer<T>(t){}
virtual ~ObserverBing(){cout<<"析构子类ObserverBing"<<endl;}
virtual void Draw(){cout<<"画一个值为:"<<Observer<T>::m_Value<<" 的饼状图"<<endl;}
};
template<class T>
class ObserverQuxian:public Observer<T>
{
public:
ObserverQuxian(T t):Observer<T>(t){}
virtual ~ObserverQuxian(){cout<<"析构子类ObserverQuxian"<<endl;}
virtual void Draw(){cout<<"画一个值为:"<<Observer<T>::m_Value<<" 的曲线图"<<endl;}
};
template<class T>//T,基本类型,U 是Observer<T>
class Subject
{
protected:
T t_Value;
list<Observer<T>*> m_List;
public:
Subject(T t):t_Value(t){}
~Subject(){
cout<<"------------------开始清除Observer"<<endl;
list<Observer<T>*>::iterator it = m_List.begin(),itend = m_List.end();
for(; it != itend; it++){
delete *it;
}
m_List.clear();
}
void SetValue(T t){
if (t_Value == t){//对于重复值不做处理
return;
}
t_Value = t;
list<Observer<T>*>::iterator it = m_List.begin(),itend = m_List.end();
for(; it != itend; it++){
(*it)->Update(t);
}
}
virtual T GetValue(){return t_Value;}
virtual void Attach(Observer<T>* p){
list<Observer<T>*>::iterator it = m_List.begin(),itend = m_List.end();
if(std::find(it,itend,p) == itend){
m_List.push_back(p);
}else{
cout<<"不好意思,加重复了"<<endl;
}
}
virtual void Dettach(Observer<T>* p){
list<Observer<T>*>::iterator it = m_List.begin(),itend = m_List.end(),itRes;
itRes = std::find(it,itend,p);
if(itRes == itend){
cout<<"不好意思,没有,删除不了"<<endl;
}else{
delete *itRes;
m_List.erase(itRes);
}
}
};
template<class T>
void Do(Subject<T>* sub,T nInit,T t1,T t2,T t3)
{
Observer<T>* pZhu = new ObserverZhu<T>(nInit);
Observer<T>* pBing = new ObserverBing<T>(nInit);
Observer<T>* pQuxian = new ObserverQuxian<T>(nInit);
sub->Attach(pZhu);
sub->Attach(pBing);
sub->Attach(pQuxian);
cout<<"------------------三个图全"<<endl;
sub->SetValue(t1);
sub->SetValue(t2);
sub->SetValue(t3);
sub->Dettach(pBing);
cout<<"------------------应该少饼图"<<endl;
sub->SetValue(t1);
sub->SetValue(t2);
sub->SetValue(t3);
cout<<endl<<"------------------清除垃圾"<<endl;
delete sub;
}
int main(int argc, char *argv[])
{
cout<<"int ++++++++++++++++++++"<<endl;
Do(new Subject<int>(0),0,5,15,25);
cout<<"float ++++++++++++++++++++"<<endl;
Do(new Subject<float>(0.0f),0.0f,5.2f,15.2f,25.2f);
cout<<"string ++++++++++++++++++++"<<endl;
Do(new Subject<string>(""),string(""),string("w"),string("c"),string("h"));
system("PAUSE");
return EXIT_SUCCESS;
}