抽象访问者(Visitor):声明所有访问者需要的接口
具体访问者(ConcreteVisitor):实现抽象访问者声明的接口
抽象节点元素(Element):提供一个接口,能够接受访问者作为参数传递给节点元素
具体节点元素(ConcreteElement):实现抽象节点元素声明的接口
结构对象(ObjectStructure):提供一个接口,能够访问到所有的节点元素,一般作为一个集合特有节点元素的引用
客户端(Client):分别创建访问者和节点元素的对象,调用访问者访问变量节点元素
visitor
package design.pattern.visitor; public interface Visitor { public void visit(Element element); }
element
package design.pattern.visitor; public abstract class Element { protected String type; public Element(String type) { this.type = type; } public void accept(Visitor visitor) { visitor.visit(this); } public String getType() { return this.type; } }
objectstructure
package design.pattern.visitor; public class ObjectStructure { private Element arr = new ConcreteElement("ConcreteElement"); private Visitor visitor; public void setVisitor(Visitor visitor) { this.visitor = visitor; } public void print() { if (null == visitor) throw new RuntimeException(); arr.accept(visitor); } }
concreteelement
package design.pattern.visitor; public class ConcreteElement extends Element { public ConcreteElement(String type) { super(type); } }
concretevisitora
package design.pattern.visitor; public class ConcreteVisitorA implements Visitor { @Override public void visit(Element element) { System.out.println("ConcreteVisitorA visit " + element.getType()); } }
concretevisitorb
package design.pattern.visitor; public class ConcreteVisitorB implements Visitor { @Override public void visit(Element element) { System.out.println("ConcreteVisitorB visit " + element.getType()); } }