#include <iostream>
#include <list>
using namespace std;
//
struct IElement;
struct IVisitor
{
public:
virtual ~IVisitor() { }
virtual void VisitFood(IElement *pElement) = 0;
virtual void VisitDrink(IElement *pElement) = 0;
};
struct IElement
{
public:
IElement(string name) : m_name(name) { }
virtual ~IElement() { }
virtual void Accept(IVisitor *pVisitor) = 0;
string getName() { return m_name; }
private:
string m_name;
};
//
class CCashier : public IVisitor
{
public:
virtual ~CCashier() { }
virtual void VisitFood(IElement *pElement) { cout<<"Cashier visit "<<pElement->getName().c_str()<<endl; }
virtual void VisitDrink(IElement *pElement) { cout<<"Cashier visit "<<pElement->getName().c_str()<<endl; }
};
class CBuyer : public IVisitor
{
public:
virtual ~CBuyer() { }
virtual void VisitFood(IElement *pElement) { cout<<"Buyer visit "<<pElement->getName().c_str()<<endl; }
virtual void VisitDrink(IElement *pElement) { cout<<"Buyer visit "<<pElement->getName().c_str()<<endl; }
};
//
class CFood : public IElement
{
public:
CFood(string name) : IElement(name) { }
virtual ~CFood() { }
virtual void Accept(IVisitor *pVisitor) { pVisitor->VisitFood(this); }
};
class CDrink : public IElement
{
public:
CDrink(string name) : IElement(name) { }
virtual ~CDrink() { }
virtual void Accept(IVisitor *pVisitor) { pVisitor->VisitDrink(this); }
};
//
class CObjects
{
public:
void Add(IElement *pElement) { m_pElementList.push_back(pElement); }
void Remove(IElement *pElement) { m_pElementList.remove(pElement); }
void Accept(IVisitor *pVisitor)
{
list<IElement*>::iterator ite = m_pElementList.begin();
for(; m_pElementList.end() != ite; ite++)
{
(*ite)->Accept(pVisitor);
}
}
private:
list<IElement*> m_pElementList;
};
//
void main()
{
CObjects objects;
CFood food("Food");
CDrink drink("drink");
objects.Add(&food);
objects.Add(&drink);
CCashier cashier;
objects.Accept(&cashier);
CBuyer buyer;
objects.Accept(&buyer);
}