// test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class observerBase
{
public:
virtual void answer(){};
};
class subjectBase
{
public:
virtual void register_ob(observerBase *){};
virtual void delete_ob(observerBase *){};
virtual void ask(){};
};
class subjectS: public subjectBase
{
public:
vector<observerBase*> ob_list;
void register_ob(observerBase *ob)
{
ob_list.push_back(ob);
//cout<<"push back"<<endl;
}
void delete_ob(observerBase *ob)
{
for(auto i=ob_list.begin();i!=ob_list.end();)
{
if((*i)==ob)
{
i=ob_list.erase(i);
}else
{
i++;
}
}
}
void ask()
{
cout<<"shoud i do?"<<endl;
for(auto i=ob_list.begin();i!=ob_list.end();i++)//auto == vector<observerBase*>::iterator
{
(*i)->answer();
//cout<<"answer"<<endl;
}
}
};
class devil:public observerBase
{
public:
devil(subjectBase *i)
{
i->register_ob(this);
//cout << "reg"<<endl;
}
void answer()
{
cout<<"devil said: fuck u"<<endl;
}
void leave(subjectBase *i)
{
i->delete_ob(this);
cout<<"devil said: I leave!"<<endl;
}
};
class angel: public observerBase
{
public:
angel(subjectBase *i)
{
i->register_ob(this);
//cout << "reg"<<endl;
}
void answer()
{
cout<<"angel said: yes, try!"<<endl;
}
void leave(subjectBase *i)
{
i->delete_ob(this);
cout<<"angel said: I leave!"<<endl;
}
};
class man: public observerBase
{
public:
man(subjectBase *i)
{
i->register_ob(this);
//cout << "reg"<<endl;
}
void answer()
{
cout<<"man said : I don't know too!"<<endl;
}
void leave(subjectBase *i)
{
i->delete_ob(this);
cout<<"man said : I left!"<<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
subjectS i;
devil *devil_inst = new devil((subjectBase *)&i);
angel *angel_inst = new angel((subjectBase *)&i);
man *man_inst = new man((subjectBase *)&i);
i.ask();
cout<<"========================"<<endl;
man_inst->leave((subjectBase *)&i);
i.ask();
cout<<"========================"<<endl;
devil_inst->leave((subjectBase *)&i);
i.ask();
delete devil_inst;
delete man_inst;
delete angel_inst;
return 0;
}
使用C++实现OO观察者模式
最新推荐文章于 2023-08-16 23:35:28 发布