class Element
{
public:
Element(string str) :m_name(str) {}
virtual void accept(visitor * pVist) = 0;
string getName(void) { return m_name; }
private:
string m_name;
};
class concreteElementA : public Element
{
public:
concreteElementA(string str) : Element(str) {};
void accept(visitor* pVist);
};
class concreteElementB : public Element
{
public:
concreteElementB(string str , int number) : Element(str)
,mNumber(number){};
void accept(visitor* pVist);
int getNumber(void) { return mNumber; }
private:
int mNumber;
};
class visitor
{
public:
virtual void visitorElementA(concreteElementA* pE) = 0;
virtual void visitorElementB(concreteElementB* pE) = 0;
};
class vistorA : public visitor
{
public:
void visitorElementA(concreteElementA* pE)
{
cout << "visitor A visit name" << pE->getName().c_str()<< endl;
}
void visitorElementB(concreteElementB* pE)
{
cout << "visitor A visit num " << pE->getNumber()<< endl;
}
};
class vistorB : public visitor
{
public:
void visitorElementA(concreteElementA* pE)
{
cout << "visitor B visit name" << pE->getName().c_str() << endl;
}
void visitorElementB(concreteElementB* pE)
{
cout << "visitor B visit num " << pE->getNumber()<< endl;
}
};
void concreteElementA::accept(visitor * pVist)
{
pVist->visitorElementA(this);
}
void concreteElementB::accept(visitor* pVist)
{
pVist->visitorElementB(this);
}
class objectStruct
{
private:
list<Element* > mlist;
public:
objectStruct() {}
~objectStruct()
{
for (auto it = mlist.begin(); it != mlist.end(); ++it)
{
delete *it;
}
mlist.clear();
}
void add(Element* pE)
{
mlist.push_back(pE);
}
void accept(visitor* pVist)
{
for (auto it = mlist.begin(); it != mlist.end(); ++it)
{
(*it)->accept(pVist);
}
}
};
int main()
{
objectStruct mObject;
visitor* pA = new vistorA();
visitor* pB = new vistorB();
mObject.add(new concreteElementA(string("EA")));
mObject.add(new concreteElementB(string("EB"),1001));
mObject.accept(pA);
mObject.accept(pB);
delete pA;
delete pB;
cin.get();
}