Vistor visitor mode (C ++ visitor Mode)

Source: Internet
Author: User

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;}
  
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.