Reprint Please specify source: http://blog.csdn.net/lhy_ycu/article/details/40028509
Visitor Mode (Visitor): The data structure and the action on the structure are decoupled, so that the operation set can evolve relatively freely. The visitor pattern is suitable for systems with relatively stable data structures and easy to change algorithms. The advantage of the visitor pattern is that it is easy to increase the operation because increasing the operation means adding new visitors , and its disadvantage is that it is difficult to add new data structures.
First, UML modeling:
Second, the Code implementation
/** * Visitor Mode (Visitor): The data structure and action on the structure of the decoupling, so that the operation set can be relatively free to evolve. * Visitor mode is a method of separating object data structure and behavior, which, through this separation, can achieve the effect of adding new actions to a visitor dynamically without having to make other changes. */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 ("Myvisitor The value of the property accessed is: "+ Subject.getfield ());}} Class Othervisitor implements Visitor {@Overridepublic void Visitor (Subject Subject) {System.out.println ("Othervisitor The value of the property accessed is: "+ Subject.getfield ());}} Interface Subject {/** accepts the object that will access it */public void accept (Visitor Visitor);/** gets the property to be accessed */public String GetField (); Class Mysubject implements Subject {private String name;public mysubject (String name) {this.name = name;} /** * This is the core: receive "named Visitor" to access the State or feature 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) {/** * creates object to be accessed */subject Subject = new Mysubject ("Zhang San");/** * Accept Access object: Only the Myvisitor visitor object is received here, not receive Othervisitor Visitor Object */subject.accept (New Myvisitor ());}}
Iii. Summary
Visitor pattern is a method of separating object data structure and behavior, and this separation can achieve the effect of adding new operations to a visitor dynamically without having to make other changes.
Java Design Patterns Rookie series (23) visitor pattern modeling and implementation