使用C++实现OO观察者模式

// 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值