observer模式

#include <iostream>
#include <list>

using namespace std;

// observer pattern
// 抽象类 纯虚函数
class observer
{
public:
	virtual void update(int a, int b, int c) = 0;
};

class max_observer: public observer
{
public:
	virtual void update(int a, int b, int c)
	{
		int t = a > b ? a : b;
		cout<< (t > c ? t : c)<<endl;
	}
};

class min_observer: public observer
{
public:
	virtual void update(int a, int b, int c)
	{
		int t = a < b ? a : b;
		cout<< ((t < c) ? t : c) <<endl;
	}
};

class average_observer: public observer
{
public:
	virtual void update(int a, int b, int c)
	{
		cout<< (a+b+c)/3 <<endl;
	}
};

//-------------------------------------
class subject_base
{
public:
	virtual void register_object(auto_ptr<observer> pobject) = 0;
	virtual void remove_object(auto_ptr<observer> pobject) = 0;
	virtual void notify() = 0;
};

class my_weight: public subject_base
{
public:
	my_weight(int a=0, int b=0, int c=0):m_weight_ago(a),m_weight_now(b),m_weight_later(c){}

	virtual void register_object(auto_ptr<observer> pobject)
	{
		m_list.push_back(pobject);
	}

	virtual void remove_object(auto_ptr<observer> pobject)
	{
	
	}

	virtual void notify()
	{
		for (list< auto_ptr<observer> >::iterator it = m_list.begin();\
			 it != m_list.end();\
			 ++it)
		{
			(*it)->update(m_weight_ago, m_weight_now, m_weight_later);
			//  it->update(,,) error
			// *it->update(,,) error
		}
	}

private:
	int m_weight_ago;
	int m_weight_now;
	int m_weight_later;
	list< auto_ptr<observer> > m_list;
};

int main(int argc, char* argv[])
{
	// auto_ptr<observer> pa = new max_observer(); error
	auto_ptr<observer> pa(new max_observer());
	auto_ptr<observer> pb(new min_observer());
	auto_ptr<observer> pc(new average_observer());

	auto_ptr<subject_base> psubject(new my_weight(1, 32, 100) );

	psubject->register_object(pa);
	psubject->register_object(pb);
	psubject->register_object(pc);

	psubject->notify();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值