1 Preface
In software design, if the architect inserts too many methods into a class to extend the functions of the class, the class will become extremely complex. A better way is to create an external class to expand it, without making too many changes to the original code.
The Visitor mode can be described using examples in daily life. You will not learn to repair pipes (that is, add more methods to the class), so you will call the pipeline Engineer ("visitor "). When he comes, he will ring the doorbell. when you open the door and let him in ("accept"), then he will come in and repair the pipe ("access ").
2. Details
2.1 Brief Introduction
The visitor pattern design has two key roles: the visitor and the elements it accesses. An element can be any object, but it is usually a node in the "part-whole" structure. Visitors know each element of a complex structure, can access the nodes of each element, and perform any operation based on the features, attributes, or operations of the element.
Visitor mode: represents an operation that acts on each element in the object structure. It allows us to define new operations acting on these elements without changing the classes of elements.
2.2 When to use
(1) A complex object structure contains many other objects. They have different interfaces (such as the combination body), but some operations depend on the specific types of objects.
(2) You need to perform many irrelevant operations on the objects in a combination body structure, but do not want these operations to "pollute" the classes of these objects. Related operations can be centralized, defined in a visitor class, and used when you need to define an operation in the visitor.
(3) classes that define complex structures are rarely modified, but new operations are often required to be added to them.
3 conclusion
The above is all content and I hope it will help you.