Java23种设计模式-行为型模式之访问者模式

时间:2024-04-29 07:07:28
// 元素接口 interface Element { void accept(Visitor visitor); } // 具体元素 class ConcreteElement implements Element { private String elementName; public ConcreteElement(String elementName) { this.elementName = elementName; } public String getElementName() { return elementName; } @Override public void accept(Visitor visitor) { visitor.visit(this); } } // 访问者接口 interface Visitor { void visit(ConcreteElement element); } // 具体访问者 class PrintVisitor implements Visitor { @Override public void visit(ConcreteElement element) { System.out.println(element.getElementName()); } } // 对象结构 class ObjectStructure { private List<Element> elements; public ObjectStructure(List<Element> elements) { this.elements = elements; } public void displayElements() { for (Element element : elements) { element.accept(new PrintVisitor()); } } } // 客户端 public class Client { public static void main(String[] args) { List<Element> elements =new ArrayList<>(); elements.add(new ConcreteElement("Element1")); elements.add(new ConcreteElement("Element2")); ObjectStructure objectStructure = new ObjectStructure(elements); objectStructure.displayElements(); } }