In the Visitor Pattern, we used a visitor class that changed the execution algorithm of the element class. In this way, the element's execution algorithm can change as the visitor changes. This type of design pattern is a behavioral model. Depending on the schema, the element object has accepted the visitor object so that the visitor object can handle the operations on the element object.
Intent: Mainly separates data structures from data operations.
Main solutions: Stable data structures and variable operational coupling problems.
When to use: requires a lot of different and unrelated operations on objects in an object structure, and you need to avoid having these operations "contaminate" the classes of these objects, using the visitor pattern. Wrap these in a class.
How to solve: Add an interface to the visited class to provide external visitors.
Key Code: There is a way to accept visitors in the data foundation class and pass their own references to the visitor.
Application example: You are a guest at a friend's house, you are a visitor, a friend accepts your visit, you make a judgment by a friend's description, and then a friend's description, this is the visitor mode.
Advantages: 1. Meet the principle of single responsibility. 2, excellent scalability. 3. Flexibility.
Disadvantages: 1. The specific elements disclose details to the visitor and violate the Dimit principle. 2. It is difficult to change specific elements. 3. Violation of the principle of dependency inversion, dependence on concrete classes, no dependence on abstraction.
Usage scenarios: 1. The classes corresponding to objects in the object structure rarely change, but it is often necessary to define new operations on this object structure. 2. There are many different and unrelated operations that need to be done on objects in an object structure. You need to avoid having these operations "contaminate" the classes of these objects, and you don't want to modify them when adding new operations.
Notes: Visitors can unify functions and can do reports, UIs, interceptors, and filters.
We will create an ComputerPart interface that defines the accept operation. Keyboard, Mouse, Monitor, and Computer are entity classes that implement the ComputerPart interface . We will define another interface ComputerPartVisitor, which defines the operation of the visitor class. Computer uses entity visitors to perform the appropriate actions.
VisitorPatternDemo, our demo class uses the Computer, ComputerPartVisitor class to demonstrate the usage of the visitor pattern.
Define an interface that represents an element.
Create an entity class that extends the above classes.
Define an interface that represents a visitor.
Create an entity visitor that implements the above classes.
Use ComputerPartDisplayVisitor to display the components of Computer.
Executing the program, outputting results:
Displaying Mouse. Displaying Keyboard. Displaying Monitor. Displaying Computer.