设计模式之访问者模式

时间:2024-06-08 07:32:00
// 元素接口 interface Element { void accept(Visitor visitor); } // 具体元素 class ConcreteElementA implements Element { @Override public void accept(Visitor visitor) { visitor.visit(this); } } class ConcreteElementB implements Element { @Override public void accept(Visitor visitor) { visitor.visit(this); } } // 访问者接口 interface Visitor { void visit(ConcreteElementA element); void visit(ConcreteElementB element); } // 具体访问者 class ConcreteVisitor implements Visitor { @Override public void visit(ConcreteElementA element) { System.out.println("ConcreteElementA is visited."); } @Override public void visit(ConcreteElementB element) { System.out.println("ConcreteElementB is visited."); } } // 对象结构(这里简化为一个简单的数组) class ObjectStructure { private List<Element> elements = new ArrayList<>(); public void attach(Element element) { elements.add(element); } public void accept(Visitor visitor) { for (Element element : elements) { element.accept(visitor); } } } // 示例 public class VisitorPatternDemo { public static void main(String[] args) { ObjectStructure objectStructure = new ObjectStructure(); objectStructure.attach(new ConcreteElementA()); objectStructure.attach(new ConcreteElementB()); Visitor visitor = new ConcreteVisitor(); objectStructure.accept(visitor); } }