Introduce
- Visitor—— Abstract Visitor
Abstract class or interface , Declare which elements visitors can access , To be specific to the procedure is visit The parameters of the method define which objects can be accessed . - ConcreteVisitor—— Specific visitors
It affects what visitors do when they visit a class , What are you going to do . - Element—— Abstract elements
Interface or abstract class , State what kind of visitors are allowed to visit , The procedure is through accept Method . - ConcreteElement—— Specific elements
Realization accept Method , Usually visitor.visit(this), Basically, a pattern has been formed . - ObjectStruture—— The structure of the object
The element producer , Generally, it can be accommodated in many different types 、 Containers with different interfaces , Such as List、 Set、 Map etc. , In the project , This character is rarely abstracted
advantage : Comply with the single responsibility principle ; Excellent scalability ; Very flexible
shortcoming : Specific elements to visitors to publish details ; It’s difficult to change specific elements ; It violates the principle of inversion of dependence
application :
- An object structure contains many class objects , They have different interfaces , And you want to do something with these objects that depends on their specific classes , In other words, it’s a situation that can’t be competent with iterator mode
- Many different and unrelated operations need to be performed on the objects in an object structure , And you want to avoid having these operations “ Pollution ” Classes for these objects
UML Class diagram :
Simple code :
Big talk design pattern No 28 Chapter , Examples of men and women
UML chart :
Code :