首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。