1、IComputerPart.java
package com.ssm.cts.pattern.visitor; public interface IComputerPart { public void accept(IComputerPartVisitor computerPartVisitor); }
2、Keyboard.java
package com.ssm.cts.pattern.visitor; public class Keyboard implements IComputerPart { @Override public void accept(IComputerPartVisitor computerPartVisitor) { computerPartVisitor.visit(this); } }
3、Monitor.java
package com.ssm.cts.pattern.visitor; public class Monitor implements IComputerPart { @Override public void accept(IComputerPartVisitor computerPartVisitor) { computerPartVisitor.visit(this); } }
4、Mouse.java
package com.ssm.cts.pattern.visitor; public class Mouse implements IComputerPart { @Override public void accept(IComputerPartVisitor computerPartVisitor) { computerPartVisitor.visit(this); } }
5、Computer.java
package com.ssm.cts.pattern.visitor; public class Computer implements IComputerPart { IComputerPart[] parts; public Computer() { parts = new IComputerPart[] { new Mouse(), new Keyboard(), new Monitor() }; } @Override public void accept(IComputerPartVisitor computerPartVisitor) { for (int i = 0; i < parts.length; i++) { parts[i].accept(computerPartVisitor); } computerPartVisitor.visit(this); } }
6、IComputerPartVisitor.java
package com.ssm.cts.pattern.visitor; public interface IComputerPartVisitor { public void visit(Computer computer); public void visit(Mouse mouse); public void visit(Keyboard keyboard); public void visit(Monitor monitor); }
7、ComputerPartDisplayVisitor.java
package com.ssm.cts.pattern.visitor; public class ComputerPartDisplayVisitor implements IComputerPartVisitor { @Override public void visit(Computer computer) { System.out.println("计算机"); } @Override public void visit(Mouse mouse) { System.out.println("鼠标"); } @Override public void visit(Keyboard keyboard) { System.out.println("键盘"); } @Override public void visit(Monitor monitor) { System.out.println("显示器"); } }
8、Demo.java
package com.ssm.cts.pattern.visitor; public class Demo { // 测试 public static void main(String[] args) { IComputerPart computer = new Computer(); computer.accept(new ComputerPartDisplayVisitor()); } }