Java Design Pattern cainiao series (23) Visitor pattern modeling and implementation
Visitor mode (Visitor): decouples the data structure and the operations acting on the structure, allowing the operation set to evolve relatively freely. The visitor mode is suitable for systems with relatively stable data structures and easily changed algorithms. The advantage of the visitor mode is that it is easy to add operations, because adding operations means adding new visitors, and its disadvantage is that it is difficult to add new data structures.
I. uml modeling:
Ii. Code Implementation
/*** Visitor mode (Visitor): decouples the data structure and the operations acting on the structure, allowing the operation set to evolve relatively freely. ** The visitor mode is a method for separating the data structure and behavior of objects, ** this allows you to dynamically add new operations to a visitor without any other modifications. */Interface Visitor {/*** Access Object ** @ param subject * object to be accessed */public void visitor (Subject subject );} class MyVisitor implements Visitor {@ Overridepublic void visitor (Subject subject) {System. out. println (the attribute value of MyVisitor access is + subject. getField () ;}} class OtherVisitor implements Visitor {@ Overridepublic void visitor (Subject subject) {System. out. println (OtherVisitor access attribute value: + subject. getField () ;}} interface Subject {/** accept the object to be accessed */public void accept (Visitor visitor ); /** get the attribute to be accessed */public String getField ();} class MySubject implements Subject {private String name; public MySubject (String name) {this. name = name;}/*** this is the core: receives the [specified Visitor] to access the status or features of our own MySubject class */@ Overridepublic void accept (visitor Visitor) {visitor. visitor (this) ;}@ Overridepublic String getField () {return name ;}} /*** client Test class ** @ author Leo */public class Test {public static void main (String [] args) {/*** create the object to be accessed */Subject subject = new MySubject (Zhang San);/*** accept the Access Object: only the MyVisitor visitor object is received here, do not receive OtherVisitor visitor objects */subject. accept (new MyVisitor ());}}
Iii. Summary
The visitor mode is a method to separate the data structure and behavior of objects. Through this separation, you can dynamically add new operations to a visitor without any other modifications.