Vistor visitor mode (C ++ visitor Mode)
The Visitor mode provides new operations for the class without damaging the class.
The Visitor mode is often used to encapsulate the update design in a class, and the class to be changed provides an interface to accept. The key technology is the dual dispatch technology. The Element class provides interfaces, which specific Visit operation is used through Accept;
Of course, if there are many modifications, You can provide more Element Visitor, but it will damage the system encapsulation and it is difficult to expand. Code in the original book of the C ++ design pattern:
#include
using namespace std;class Element;class Visitor{public:virtual ~Visitor(){}virtual void visitConElemA(Element* elm)=0;virtual void visitConElemB(Element* elm)=0;protected:Visitor(){}};class ConcreteVisitorA:public Visitor{public:ConcreteVisitorA(){};virtual ~ConcreteVisitorA(){};void visitConElemA(Element* elm){cout<<"visit A";}void visitConElemB(Element* elm){cout<<"visit B";}};class ConcreteVisitorB:public Visitor{public:ConcreteVisitorB(){};virtual ~ConcreteVisitorB(){};void visitConElemA(Element* elm){cout<<"visit A";}void visitConElemB(Element* elm){cout<<"visit B";}};class Element{public:virtual ~Element(){};virtual void Accept(Visitor* vis)=0;protected:Element(){};};class ConcreteElementA:public Element{public:ConcreteElementA(){}~ConcreteElementA(){}void Accept(Visitor* vis){cout<<"This is A interface "<
visitConElemA(this);}};class ConcreteElementB:public Element{public:ConcreteElementB(){}~ConcreteElementB(){}void Accept(Visitor* vis){cout<<"This is B interface ";vis->visitConElemB(this); }};void main(){Visitor* vis=new ConcreteVisitorA();Element* elm=new ConcreteElementA();elm->Accept(vis);delete elm;delete vis;}