【24种设计模式】观察者模式

#include <list>
#include <iostream>
using namespace std;


template <typename _type>
class observer
{
public:
	observer() {}
	virtual ~observer() {}

	virtual void update(_type& event) { }
};

template <typename _type>
class observable
{
public:
	typedef observer<_type> * value_type; 

public:
	observable() {}
	virtual ~observable() {}

 	void attach(value_type p)
 	{
 		m_observerlist.push_back(p);
 	}
 
 	void detach(value_type p)
 	{
 		m_observerlist.remove(p);
 	}

 	void fireevent(_type& event)
 	{
 		for each (value_type item in m_observerlist)
 		{
 			item->update(event);
 		} 
 	}

protected:
	list<value_type>  m_observerlist;
};
 
 
 
 
int _tmain(int argc, _TCHAR* argv[])
{
 	observer<int> ob1;
 	observer<int> ob2;
 
 	observable<int> notify;
 	notify.attach(&ob1);
 	notify.attach(&ob2);
 
 	int i = 1;
 	notify.fireevent(i);


	system("pause");

	return 0;
}


你可能感兴趣的:(【24种设计模式】观察者模式)