The visitor mode provides new new operations for the class without destroying the class.
Visitor mode is often used to encapsulate the updated design in a class, and the class to be changed to provide an acceptance interface, the key technology is the dual dispatch technology, the element class provides interfaces, through the accept implementation of the specific use of which specific visit operation;
of course, if there are a lot of changes, you can provide more element visitor, but it will destroy the package of the system, and it is difficult to expand. code in the original book of C + + design mode:
#include <iostream>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 was A interface" <<endl;vis->visitconelema (this);}; Class Concreteelementb:public Element{public:concreteelementb () {}~concreteelemeNtB () {}void Accept (visitor* Vis) {cout<< "This is a B interface"; Vis->visitconelemb (this); }};void Main () {visitor* vis=new concretevisitora (); element* elm=new Concreteelementa (); elm->accept (Vis);d elete elm;delete vis;}
Vistor Visitor Mode (c + + visitor mode)