demo
public class Visitor {
public static void main(String[] args) {
ObjectStructure objectStructure = new ObjectStructure();
objectStructure.acccept(new ConcreteVisitor());
}
}
abstract class Element{
public abstract void work();
public abstract void accept(AbstractVisitor visitor);
}
class ElementA extends Element{
@Override
public void work() {
System.out.println("A ele work");
}
@Override
public void accept(AbstractVisitor visitor) {
visitor.visit(this);
}
}
class ElementB extends Element{
@Override
public void work() {
System.out.println("B ele work");
}
@Override
public void accept(AbstractVisitor visitor) {
visitor.visit(this);
}
}
abstract class AbstractVisitor{
public abstract void visit(ElementA elementA);
public abstract void visit(ElementB elementB);
}
class ConcreteVisitor extends AbstractVisitor{
@Override
public void visit(ElementA elementA) {
System.out.println("visit A");
elementA.work();
}
@Override
public void visit(ElementB elementB) {
elementB.work();
}
}
class ObjectStructure {
ElementA elementA = new ElementA();
ElementB elementB = new ElementB();
public void acccept(AbstractVisitor v) {
this.elementA.accept(v);
this.elementB.accept(v);
}
}