class ConcreteVisitor1 extends Visitor {
@Override
public void VisitConcreteElementA(ConcreteElementA elementA) {
System.out.println(this.getClass().getName() + " 访问 " + elementA.getClass().getName());
}
@Override
public void VisitConcreteElementB(ConcreteElementB elementB) {
System.out.println(this.getClass().getName() + " 访问 " + elementB.getClass().getName());
}
}
class ConcreteVisitor2 extends Visitor {
@Override
public void VisitConcreteElementA(ConcreteElementA elementA) {
System.out.println(this.getClass().getName() + " 访问 " + elementA.getClass().getName());
}
@Override
public void VisitConcreteElementB(ConcreteElementB elementB) {
System.out.println(this.getClass().getName() + " 访问 " + elementB.getClass().getName());
}
}
class ConcreteElementA extends Element {
@Override
public void Accept(Visitor visitor) {
visitor.VisitConcreteElementA(this);
}
}
class ConcreteElementB extends Element {
@Override
public void Accept(Visitor visitor) {
visitor.VisitConcreteElementB(this);
}
}
class ObjectStructure {
private List<Element> elements = new ArrayList<Element>();
public void Attach(Element element) {
elements.add(element);
}
public void Detach(Element element) {
elements.remove(element);
}
public void Accept(Visitor visitor) {
for (Element elem : elements) {
elem.Accept(visitor);
}
}
}
public class VisitorPattern {
public static void main(String[] args) {
ObjectStructure o = new ObjectStructure();
o.Attach(new ConcreteElementA());
o.Attach(new ConcreteElementB());
ConcreteVisitor1 v1 = new ConcreteVisitor1();
ConcreteVisitor2 v2 = new ConcreteVisitor2();
o.Accept(v1);
o.Accept(v2);
}
}
复制代码
ConcreteVisitor1 访问 ConcreteElementA
ConcreteVisitor1 访问 ConcreteElementB
ConcreteVisitor2 访问 ConcreteElementA
ConcreteVisitor2 访问 ConcreteElementB