In the Visitor Pattern, we use a Visitor class that changes the execution algorithm of the element class. In this way, the element’s execution algorithm can change as visitors change. This type of design pattern is behavioral. According to the schema, the element object already accepts the visitor object so that the visitor object can process operations on the element object.
- Define an interface that represents an element.
/** * 1. Define an interface that represents an element. * @author mazaiting */ public interface ComputerPart { public void accept(ComputerPartVisitor visitor); }Copy the code
- Create an entity class that extends the above classes.
/** * 2. Create an entity class that extends the above classes. * @author mazaiting */ public class Computer implements ComputerPart{ public void accept(ComputerPartVisitor visitor) { visitor.visit(this); }} /** * 2. Create an entity class that extends the above classes. * @author mazaiting */ public class Keyboard implements ComputerPart{ public void accept(ComputerPartVisitor visitor) { visitor.visit(this); }} /** * 2. Create an entity class that extends the above classes. * @author mazaiting */ public class Monitor implements ComputerPart{ public void accept(ComputerPartVisitor visitor) { visitor.visit(this); }} /** * 2. Create an entity class that extends the above classes. * @author mazaiting */ public class Mouse implements ComputerPart{ public void accept(ComputerPartVisitor visitor) { visitor.visit(this); }}Copy the code
- Define an interface that represents a visitor.
/** * 3. Define an interface to represent visitors. * @author mazaiting */ public interface ComputerPartVisitor { /*public void visit(Computer computer); public void visit(Mouse mouse); public void visit(Keyboard keyboard); public void visit(Monitor monitor); */ public <T> void visit(T t); }Copy the code
- Create an entity visitor that implements the above classes.
/** * 4. Create an entity visitor that implements the above classes. * @author mazaiting */ public class ComputerPartDisplayVisitor implements ComputerPartVisitor { public <T> void visit(T t) { System.out.println(t.getClass().getName()); } /*public void visit(Computer computer) { System.out.println("Displaying Computer."); } public void visit(Mouse mouse) { System.out.println("Displaying Mouse."); } public void visit(Keyboard keyboard) { System.out.println("Displaying Keyboard."); } public void visit(Monitor monitor) { System.out.println("Displaying Monitor."); * /}}Copy the code
- Use ComputerPartDisplayVisitor to show part of the Computer.
/ * * * 5. Use the ComputerPartDisplayVisitor to display * part of the Computer. * @author mazaiting */ public class Client { public static void main(String[] args) { ComputerPart computer = new Computer(); computer.accept(new ComputerPartDisplayVisitor()); }}Copy the code
- Print the result
com.mazaiting.visitor.Computer
Copy the code
reference
www.jianshu.com/p/d521a3699…