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