Visitor mode: The operation is independent of the class, and the class accepts the corresponding visitor according to the operation you need.
The advantage of doing so is that if you need to implement a new operation, the structure of the class does not need to be changed, especially the entire class level. If you want to change, the cost is relatively high.
By using the visitor mode, you can ensure that the added operations are simple and convenient, and comply with the OCP.
The visitor mode has a scary concept: Double dispatch. In fact, the so-called double dispatch only means that to define an operation, two objects are required to decide, these two objects are element objects and visitor objects. For example, the execution results of elementa objects accepting visitora objects are different from those of visitorb objects.
The following example shows the meaning of "Double dispatch.
// Visitor. cpp
# Include <iostream>
# Include <string>
Using namespace STD;
Class element;
/** // The visitor class and its subclass
Class visitor
...{
Public:
Virtual void visit (element * E) = 0;
};
Class visitora: public visitor
...{
Public:
Virtual void visit (element * E)
...{
Cout <"perform operation a" <Endl;
}
};
Class visitorb: public visitor
...{
Public:
Virtual void visit (element * E)
...{
Cout <"execute Operation B" <Endl;
}
};
/** // Element class and its subclass
Class Element
...{
Public:
Virtual void accept (visitor * V)
...{
Cout <m_name;
V-> visit (this );
}
String & getname ()
...{
Return m_name;
}
Protected:
String m_name;
};
Class elementa: public element
...{
Public:
Elementa (string S)
...{
M_name = s;
}
};
Class elementb: public element
...{
Public:
Elementb (string S)
...{
M_name = s;
}
};
/** // Test the above class
Void main ()
...{
Elementa EA ("element ");
Elementb EB ("Element B ");
Visitora Va;
Visitorb Vb;
// Double dispatch. "receiver" and "visitor" determine an operation.
EA. Accept (& VA );
EA. Accept (& VB );
EB. Accept (& VA );
EB. Accept (& VB );
}
With the visitor, we can see that if we need to implement a new operation in the element class, we do not need to modify the structure of the class,
For example, if the class is encapsulated in DLL or com, we don't need to recompile it. We only need to define a new visitor, such as visitorc, and then accept it in element. Everything is OK!