[design mode] 23 Visitor mode visitor pattern

Source: Internet
Author: User

In the book "Design pattern: The basis of reusable object-oriented software" in Gof, the visitor pattern is said to represent an operation that acts on elements in an object's structure. It allows you to define new actions that act on these elements without changing the class of each element. The visitor pattern frees up the coupling between the data structure and the operations acting on the structure, allowing the set of operations to evolve relatively freely. The purpose of this pattern is to separate the processing from the data structure. The visitor pattern makes it easy to add new operations because adding new operations means adding a new visitor. The visitor pattern concentrates the behavior on a visitor object.

The first contact, the definition will appear obscure and difficult to understand, it's okay, LZ to accompany you together 1.1 points in the analysis of the key points mentioned in the definition.

First of all, the first sentence, said to be a function of an object structure of the elements of the operation , here are mentioned three things, one is the object structure, one is the elements, one is the operation. So we can understand that there is an operation that acts on a number of elements that belong to an object structure.

Well, the most critical second sentence comes, and it says that using the visitor pattern allows us to define new actions that act on these elements without changing the individual element classes . The key point here is that the first half of the sentence, that is, without changing the elements of the premise, in this premise to define the new operation is the essence of the visitor pattern essence.

Visitor Interface: It defines the behavior of each element, its parameters are accessible elements, the number of methods in theory and the number of elements (element implementation class number) is the same, from this point is not difficult to see, The visitor pattern requires that the number of element classes cannot be changed (meaning that if the number of element classes changes frequently, it is not appropriate to use the visitor pattern).

Concretevisitor: A specific visitor, it needs to give the specific behavior that arises when each element class is accessed.

Element interface: An interface of elements that defines a method of receiving a visitor (accept), meaning that each element is accessible to the visitor.

Concreteelement: A concrete element class that provides a concrete implementation of an accepted access method, and this particular implementation typically uses a method provided by the visitor to access the element class.

Objectstructure: This is the object structure mentioned in the definition, the object structure is an abstract expression, the specific point can be understood as a container or compound object characteristics of the class, it will contain a set of elements (element), and can iterate over these elements for visitors to access.

Of the top five characters, the most important is the last one, the so-called visitor pattern, that is, in order to allow visitors to easily access the structure of the object exists. For examples of visitor patterns, many articles and documents use examples of men and women, so the LZ does not repeat here.

#include <iostream>#include<vector>#include<string>#include<algorithm>using namespacestd;classVisitor;//Element ObjectclassElement { Public:         Virtual voidAccept (Visitor *pvisitor) =0;};classConcreteelementa: PublicElement {Private:        stringM_name;  Public: Concreteelementa (); stringGetName () {returnM_name;} voidAccept (Visitor *pvisitor);};classCONCRETEELEMENTB: PublicElement {Private:        stringM_name;  Public: Concreteelementb (); stringGetName () {returnM_name;} voidAccept (Visitor *pvisitor);};classvisitor{ Public:        Virtual voidVisitconcreteelementa (concreteelementa *pelementa) =0; Virtual voidVISITCONCRETEELEMENTB (concreteelementb *pelementb) =0;};classConcreteVisitor1: Publicvisitor{ Public:        voidVisitconcreteelementa (Concreteelementa *Pelementa); voidVISITCONCRETEELEMENTB (CONCRETEELEMENTB *pelementb);};voidConcretevisitor1::visitconcreteelementa (Concreteelementa *Pelementa) {cout<<"Visitor1 vist"<< Pelementa->getname () <<Endl;}voidCONCRETEVISITOR1::VISITCONCRETEELEMENTB (CONCRETEELEMENTB *PELEMENTB) {cout<<"Visitor1 vist"<< Pelementb->getname () <<Endl;}classConcreteVisitor2: Publicvisitor{ Public:        voidVisitconcreteelementa (Concreteelementa *Pelementa); voidVISITCONCRETEELEMENTB (CONCRETEELEMENTB *pelementb);};voidConcretevisitor2::visitconcreteelementa (Concreteelementa *Pelementa) {cout<<"Visitor2 vist"<< Pelementa->getname () <<Endl;}voidCONCRETEVISITOR2::VISITCONCRETEELEMENTB (CONCRETEELEMENTB *PELEMENTB) {cout<<"Visitor2 vist"<< Pelementb->getname () <<Endl;} Concreteelementa::concreteelementa () {m_name="Concreteelementa";}voidConcreteelementa::accept (Visitor *pvisitor) {Pvisitor->visitconcreteelementa ( This);} Concreteelementb::concreteelementb () {m_name="CONCRETEELEMENTB";}voidConcreteelementb::accept (Visitor *pvisitor) {Pvisitor-&GT;VISITCONCRETEELEMENTB ( This);}//Objectstructureà࣬äü㶾ùëüµäôªëø£¬¿éòôìṩò»¸ö¸ß²ãµä½ó¿úòôôêðí Ãîêõß Ãîêëüµäôªëøclassobjectstructure{ Public:        voidAttach (Element *pelement); voidDetach (Element *pelement); voidAccept (Visitor *pvisitor); Private: Vector<element *>elements;};voidObjectstructure::attach (Element *pelement) {Elements.push_back (pelement);}voidObjectstructure::D Etach (Element *pelement) {Vector<element *>::iterator it =Find (Elements.begin (), Elements.end (), pelement); if(It! =Elements.end ())    {elements.erase (IT); }}voidObjectstructure::accept (Visitor *pvisitor) {    //Ϊã¿ò»¸öelementéèöãvisitor£¬½øðð¶ôó¦µä²ùx÷     for(vector<element *>::const_iterator it = Elements.begin (); It! = Elements.end (); + +it) {        (*it)Accept (Pvisitor); }}intMain () {objectstructure*pobject =Newobjectstructure; Concreteelementa*pelementa =NewConcreteelementa; CONCRETEELEMENTB*PELEMENTB =NewCONCRETEELEMENTB; Pobject-Attach (Pelementa); Pobject-Attach (PELEMENTB); ConcreteVisitor1*pvisitor1 =NewConcreteVisitor1; ConcreteVisitor2*pvisitor2 =NewConcreteVisitor2; Pobject-Accept (PVisitor1); Pobject-Accept (PVISITOR2); if(PVISITOR2)DeletePVisitor2; if(PVisitor1)DeletePVisitor1; if(PELEMENTB)DeletePELEMENTB; if(Pelementa)DeletePelementa; if(pobject)DeletePobject; return 0;}


Visitor1 vist ConcreteElementAVisitor1 vist ConcreteElementBVisitor2 vist ConcreteElementAVisitor2 vist Concreteelementb

Visitor (visitor): declares a visit operation for each class concreteelement in the object structure. The name and characteristics of the operation identify the class that sent the visit request to that visitor. This allows the visitor to determine the specific class of elements being accessed. This allows the visitor to access it directly through the element's specific interface.
Concretevisitor (Specific visitor): Implements each action declared by visitor. Each operation implements part of the algorithm, and the algorithm fragment is the class that corresponds to the object in the structure. Concretevisitor provides the context for the algorithm and stores its local state. This state often accumulates results in the process of traversing the structure.
Element: Defines an accept operation that takes a visitor as a parameter.
Concreteelement (specific Element): Implements the accept operation, which takes a visitor as a parameter.
Objectstructure (object structure): The ability to enumerate its elements while providing a high-level interface to allow the visitor to access its elements.

Use occasions
      1. An object structure contains many classes of objects, and they have different interfaces, and you want to implement some operations that depend on their specific classes for these objects;
      2. You need to do many different and unrelated operations on objects in an object structure, and you want to avoid classes that let these actions "pollute" those objects. Visitor allows you to centralize related operations in a single class;
      3. When the object structure is shared by many applications, use visitor mode to have each app contain only the actions that need to be used;
      4. Classes that define the structure of an object rarely change, but it is often necessary to define new operations on this structure. Changing the object structure class requires redefining the interface to all visitors, which can take a significant cost. If the object structure classes often change, it might be better to define them in these classes

The basic idea of the visitor pattern is as follows: First, you have an object structure consisting of many objects, which is the objectstructure in the above code, and the classes of these objects have an accept method to receive the visitor object; The visitor is an interface that has a visit method, This method makes different operations on different types of elements in the object structure accessed, and during one access to the object structure, we traverse the entire object structure, implement an accept method for each element, and callback the visitor's visit method in each element's accept method, This allows the visitor to handle every element of the object structure. We can design different visitor classes for the object structure to do different things.

The Visitor mode provides new new operations for the class without destroying the class. The key to the Visitor model is the two-point
(double-dispatch) Technology "Note 1". The C + + language supports single dispatch.
The Accept () operation in Visitor mode is a double-Dispatch operation. Specifically call which specific Accept
() operation, there are two determinants: 1) the type of element. Because the Accept () is a polymorphic operation, it requires a
The subclass of the element type of the body can determine exactly which Accept () implementation to invoke, 2) the type of Visitor.
The Accept () operation has a parameter (visitor* Vis), which determines the actual class of Visitor actually passed in to
To decide specifically which visitconcrete () implementation to invoke.

[design mode] 23 Visitor mode visitor pattern

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.