概念:一个作用于某对象结构中的各元素的操作。它使你可用在不改变各元素的类的前提下定义作用于这些元素的新操作。
核心:访问者模式适用于数据结构相对于稳定的系统,Element不能随意扩展,扩展会导致开闭原则违反,导致visitor变更严重
访问者模式
java代码
public class VisitorTest {
public static void main(String[] args) {
ConcreteVisitor1 v1 = new ConcreteVisitor1();
ConcreteVisitor2 v2 = new ConcreteVisitor2();
Element elementA = new ConcreteElementA();
Element elementB = new ConcreteElementB();
elementA.Accept(v1);
elementB.Accept(v1);
elementB.Accept(v2);
elementB.Accept(v2);
}
}
public abstract class Visitor {
public abstract void VisitConcreteElementA();
public abstract void VisitConcreteElementB();
}
public class ConcreteVisitor1 extends Visitor {
@Override
public void VisitConcreteElementA() {
System.out.println("成功的A是十分骄傲的");
}
@Override
public void VisitConcreteElementB() {
System.out.println("成功的B是十分骄傲的");
}
}
public class ConcreteVisitor2 extends Visitor {
@Override
public void VisitConcreteElementA() {
System.out.println("失败时A是十分沮丧的");
}
@Override
public void VisitConcreteElementB() {
System.out.println("失败时B是平常心的");
}
}
public abstract class Element {
public abstract void Accept(Visitor visitor);
}
public class ConcreteElementA extends Element {
@Override
public void Accept(Visitor visitor) {
visitor.VisitConcreteElementA();;
}
}
public class ConcreteElementB extends Element {
@Override
public void Accept(Visitor visitor) {
visitor.VisitConcreteElementB();
}
}