Overview
Indicates an element operation acting on an object structure. It allows you to define new operations acting on these elements without changing the element classes. It frees you from the coupling between the data structure and the operations acting on the structure, the combination of operations can evolve relatively freely. The advantage is that it is easy to add new operations, because adding a new operation means adding a new visitor, and the visitor mode will concentrate the relevant behavior into an access object.
Intention
You can access operations of different types of elements through a unified interface, and use this interface to add new operations without changing the elements.
Structure chart
Role description:
Visitor role: declares an access operation interface for the specific element role in the object structure. The name and parameters of this operation interface identify the specific element role that sends an access request to a specific visitor. In this way, the visitor can directly access the element through a specific interface of the element role.
A specific Visitor role (Concrete Visitor): implements each operation declared by the Visitor role (Visitor.
Element: defines an Accept operation, which takes a visitor as the parameter.
Concrete Element: implements the Accept operation provided by the Element role.
Object Structure role: a required role in the visitor mode. It must have the following features: it can enumerate its elements; it can provide a high-level interface to allow the visitor to access its elements; it can be a combination (combination mode) or a set, such as a list or an unordered set.
Examples in life
For example, there is A park with one or more different components. There are multiple visitors to the park: Cleaner A is responsible for cleaning part A of the park, and cleaner B is responsible for cleaning part B of the park, park managers are responsible for checking whether all matters are completed, and superiors can inspect the park.
Example Diagram
In life, boys and girls have different forms when they fall in love. The question and method of thinking are also different. We design a visitor mode, as shown in the following example:
Code Design
Create Person. cs First:
Html # viewSource "commandName =" viewSource "highlighterId =" highlighter_919847 "> view sourceprint?
1 |
public interface Person |
3 |
string Accept(Visitor visitor); |
Create Boy. cs again:
View sourceprint?
01 |
public class Boy : Person |
03 |
# Region Person Member |
05 |
public string Accept(Visitor visitor) |
07 |
return visitor.Visit(this); |