Visitor patterns decouple The data structure from the action on the structure, allowing the set of operations to evolve relatively freely. The visitor pattern is suitable for systems with relatively stable and variable data structures. Because the visitor pattern makes it easier to increase the algorithm operation. If the system data structure object is easy to change, often new data objects are added, it is not appropriate to use the visitor pattern. The advantage of the visitor pattern is that it is easy to increase the operation because increasing the operation means adding new visitors. The visitor pattern centralizes the behavior in a visitor object, and its change does not affect the system data structure. The disadvantage is that it is difficult to add new data structures. --from Encyclopedia
Simply put, the visitor pattern is a way of separating the object's data structure and behavior, which can be achieved by adding new operations to a visitor dynamically without having to make other changes. Simple diagram:
Take a look at the original code: A visitor class that holds the object to be accessed,
[Java]View Plaincopy
- Public Interface Visitor {
- Public void Visit (Subject sub);
- }
[Java]View Plaincopy
- Public class Myvisitor implements Visitor {
- @Override
- Public void Visit (Subject sub) {
- SYSTEM.OUT.PRINTLN ("Visit the Subject:" +sub.getsubject ());
- }
- }
The subject class, accept method, accepts the object that will access it, Getsubject () Gets the property that will be accessed,
[Java]View Plaincopy
- Public Interface Subject {
- Public void Accept (Visitor Visitor);
- Public String Getsubject ();
- }
[Java]View Plaincopy
- Public class Mysubject implements Subject {
- @Override
- Public void Accept (Visitor Visitor) {
- Visitor.visit (this);
- }
- @Override
- Public String Getsubject () {
- return "Love";
- }
- }
Test:
[Java]View Plaincopy
- Public class Test {
- Public Static void Main (string[] args) {
- Visitor Visitor = new myvisitor ();
- Subject sub = new mysubject ();
- Sub.accept (visitor);
- }
- }
Output: Visit the Subject:love
This pattern applies to scenarios: if we want to add new functionality to an existing class, there are a few things to consider: 1. Does the new feature have compatibility issues with existing features? 2. Will I need to add it again? 3. What if the class does not allow the code to be modified? In the face of these problems, the best solution is to use the visitor pattern, the visitor pattern for the relatively stable structure of the system, the data structure and algorithm decoupling,
Visitor Mode (Visitor)