interface Visitor {
void visit(ElementA elementA);
void visit(ElementB elementB);
}
class ConcreteVisitor implements Visitor {
@Override
public void visit(ElementA elementA) {
System.out.println("Visitor is visiting ElementA");
}
@Override
public void visit(ElementB elementB) {
System.out.println("Visitor is visiting ElementB");
}
}
接下来,我们需要实现两个不同的元素,它们都实现了accept方法,将自身传递给访问者:
interface Element {
void accept(Visitor visitor);
}
class ElementA implements Element {
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
class ElementB implements Element {
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
最后,我们可以在客户端中使用这些类:
public class Client {
public static void main(String[] args) {
ElementA elementA = new ElementA();
ElementB elementB = new ElementB();
Visitor visitor = new ConcreteVisitor();
elementA.accept(visitor);
elementB.accept(visitor);
}
}