public interface Visitor {
//访问元素A,相当于给元素A增加功能
void visitConcreteElementA(ConcreteElementA elementA);
//访问元素B,相当于给元素B增加功能
void visitConcreteElementB(ConcreteElementB elementB);
}
public abstract class Element {
public abstract void accept(Visitor visitor);
}
//具体元素对象
public class ConcreteElementA extends Element{
@Override
public void accept(Visitor visitor) {
visitor.visitConcreteElementA(this);
}
}
//具体元素对象
public class ConcreteElementB extends Element{
@Override
public void accept(Visitor visitor) {
visitor.visitConcreteElementB(this);
}
}
//实现某一功能的具体访问者
public class ConcreteVisitor1 implements Visitor{
@Override
public void visitConcreteElementA(ConcreteElementA elementA) {
}
@Override
public void visitConcreteElementB(ConcreteElementB elementB) {
}
}
//实现某一功能的具体访问者
public class ConcreteVisitor2 implements Visitor{
@Override
public void visitConcreteElementA(ConcreteElementA elementA) {
}
@Override
public void visitConcreteElementB(ConcreteElementB elementB) {
}
}
public class ObjectStructure {
private Collection<Element> collection = new ArrayList<>();
public void addElement(Element e){
this.collection.add(e);
}
//提供给客户端使用
public void handleRequest(Visitor visitor){
for (Element e : collection){
e.accept(visitor);
}
}
}
public class Client {
public static void main(String[] args) {
ObjectStructure os = new ObjectStructure();
os.addElement(new ConcreteElementA());
os.addElement(new ConcreteElementB());
Visitor visitor = new ConcreteVisitor1();
os.handleRequest(visitor);
}
}