Visitor pattern intent
Person has sub-classes: Boy and Girl; Methods: say (), eat (int I), and walk (). It is said that eat is related to height, mood, and so on, and there are very complicated algorithms... it is said that the Code of say () and walk () is put together, it will appear unprofessional ......
The Code of Person is implemented by sub-classes.Person is very easy to extend new subclass.
Package method. visitor; public abstract class Person {public abstract void accept (Visitor v);/* public abstract String say (); public abstract int eat (int I ); // long meat public abstract void walk ();*/}
However, because the code of these methods of Person will be scattered in Boy and Gril, "making the entire system hard to understand", more importantly,Difficulties in adding new methods to Person-- Violation of OCP, the entire class level needs to be modified. Therefore, the visitor mode is available. Starting from the structure, the visitor Mode 2 shows the fact that the visitor mode can be used as long as dual-assignment is involved. But the starting point of GoF is to crosstab the Person hierarchy into a Visitor hierarchy.
Visitors perform special checks.
Person Has n sub-classes and m methods. If it is converted to Visitor, there are m sub-classes and n methods.N * m = m * n. The best use cases of visitor mode:The larger the value of m, the smaller the value of n, the better. In other words, there are many visitor types and few element types in the object structure, which is suitable for the visitor mode..
After reconstruction, the methods of Person are "say ()", "eat (int I)", and "walk ()" into the access subclass, leaving only accept. Visitor will access the Child class of Person.
Package method. visitor;/*** @ author yqj2065 * @ version 2014.9 */public abstract class Visitor {public abstract void visit (Person p); abstract void visitBoy (); abstract void visitGirl ();} package method. visitor; import static tool. print. *; public class SayVisitor extends Visitor {public void visit (Person p) {p. accept (this) ;}@ Override void visitBoy () {// Boy. say pln ("Boy. say ") ;}@ Override void visitGirl () {pln (" Girl. say ") ;}}// EatVisitor, brief visitor
Therefore, (Visitor or) EatVisitor indicates"
An operation that acts on each element in an object structure", EatVisitor indicates the Person's eat (int I );
Therefore, Visitor"This allows you to define new operations that act on these elements without changing the classes of each element.". To add a song () operation to a Person, add a SongVisitor.
Adding operations to Person now makes it easy to add sub-classes. In the past, the opposite was true.
Yqj2065 people do not like GoF as a starting point, and it is troublesome for visitors to treat Person methods such as eat (int I) when parameters and return values are involved.
In most cases, visitors useVoid visitBoy (Boy). In visitor Mode 2, void visitBoy () is a bit simple.