首页 > 代码库 > Visitor

Visitor

#include <iostream>#include <vector>using namespace std;#define DESTROY_POINTER(ptr) if (ptr) { delete ptr; ptr = NULL; }class Element;class Visitor{public:    virtual void Visit(Element* pElement)=0;};class ConcreteVisitorA : public Visitor{public:    void Visit(Element* pElement);};class ConcreteVisitorB : public Visitor{public:    void Visit(Element* pElement);};class Element{public:    virtual void Accept(Visitor* pVisitor)=0;    virtual void Interface1()=0;    virtual void Interface2()=0;};class ConcreteElementA : public Element{public:    void Accept(Visitor* pVisitor)    {        pVisitor->Visit(this);    }    void Interface1() { cout<<"ConcreteElementA::Interface1"<<endl; }    void Interface2() { cout<<"ConcreteElementA::Interface2"<<endl; }};class ConcreteElementB : public Element{public:    void Accept(Visitor* pVisitor)    {        pVisitor->Visit(this);    }    void Interface1() { cout<<"ConcreteElementB::Interface1"<<endl; }    void Interface2() { cout<<"ConcreteElementB::Interface2"<<endl; }};void ConcreteVisitorA::Visit(Element* pElement){    pElement->Interface1();}void ConcreteVisitorB::Visit(Element* pElement){    pElement->Interface2();}class Structure{public:    virtual ~Structure()    {        for (unsigned int i = 0; i < m_elementList.size(); i++)        {            delete m_elementList[i];        }        m_elementList.clear();    }    void Accept(Visitor* pVisitor)    {        for (unsigned int i = 0; i < m_elementList.size(); i++)        {            m_elementList[i]->Accept(pVisitor);        }    }        void AddElement(Element* pElement)    {        m_elementList.push_back(pElement);    }private:    vector<Element*> m_elementList;};int main(int argc, char *argv[]){    Structure structure;    structure.AddElement(new ConcreteElementA);    structure.AddElement(new ConcreteElementB);    Visitor* pVisitorA = new ConcreteVisitorA;    Visitor* pVisitorB = new ConcreteVisitorB;        structure.Accept(pVisitorA);    structure.Accept(pVisitorB);    DESTROY_POINTER(pVisitorA);    DESTROY_POINTER(pVisitorB);    return 0;}

 

Visitor