abstract class Visitor {
public abstract void VisitConcreteElementA(ConcreteElementA elementA);
public abstract void VisitConcreteElementB(ConcreteElementB elementB);
}
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);
}
}
}