Motivation : Indicates an operation that acts on each element in an object structure. It can define new operations that act on these elements without changing the classes of each element.
Scenario: Graphic System, assuming its image type is stable, and its operation changes are available.
Structure
Code
Namespace Designpattern. Visitor
{
Public Abstract Class Shape
{< br> Public abstract void draw ();
// Second Distribution
Public abstract void Accept (shapevisitor visitor);
}
Public Class Rectangle: Shape
{
Public Override Void Draw ()
{
}
Public Override Void Accept (shapevisitor visitor)
{
Visitor. Visit (This);
}
}
Public Class Circle: Shape
{
Public Override Void Draw ()
{
}
Public Override Void Accept (shapevisitor visitor)
{
Visitor. Visit (This);
}
}
Public Class Line: Shape
{
Public Override Void Draw ()
{
}
Public Override Void Accept (shapevisitor visitor)
{
Visitor. Visit (This);
}
}
}
Namespace Designpattern. Visitor
{
Public Abstract Class Shapevisitor
{
Public Abstract Void Visit (rectangle );
Public Abstract Void Visit (circle );
Public Abstract Void Visit (line );
}
Public Class Scalevisitor: shapevisitor
{
Public Override Void Visit (rectangle)
{
}
Public Override Void Visit (circle)
{
}
Public Override Void Visit (line)
{
}
}
Public Class Movevisitor: shapevisitor
{
Public Override Void Visit (rectangle)
{
}
Public Override Void Visit (circle)
{
}
Public Override Void Visit (line)
{
}
}
}
Namespace Designpattern. Visitor
{
Public Class Application
{
Shapevisitor visitor;
Public Application (shapevisitor visitor)
{
This. Visitor=Visitor;
}
Public Void Process (shape)
{
Shape. Accept (visitor );//First Distribution
}
}
}
Key Points :
1. In this mode, the layer structure of the element class is not changed through the so-called dual-distribution, during runtime, new operations are dynamically added for each class in the class hierarchy transparently.
2. The so-called dual-distribution model contains two polymorphism distributions. The first is the polymorphism of the accept method, and the second is the polymorphism of the visit method.
3. The biggest drawback of this mode is that the extension class hierarchy (adding new element subclass) will change the visitor class. Therefore, this mode applies to "element class hierarchies are stable, but operations are subject to frequent changes ".