//抽象元素 interface IElement{ public void accept(IVisitor visitor); } //具体元素 class ElementA implements IElement{ public void accept(IVisitor visitor){ visitor.visit(this); } public void operationA(){ System.out.println(“ElementA do operationA()……”); } } class ElementB implements IElement{ public void accept(IVisitor visitor){ visitor.visit(this); } public void operationB(){ System.out.println(“ElementB do operationB()……”); } } class ElementC implements IElement{ public void accept(IVisitor visitor){ visitor.visit(this); } public void operationC(){ System.out.println(“ElementC do operationC()……”); } } //抽象访问者 interface IVisitor{ public void visit(ElementA element); public void visit(ElementB element); public void visit(ElementC element); } //具体访问者 class MyVisitor implements IVisitor{ public void visit(ElementA element){ element.operationA(); } public void visit(ElementB element){ element.operationB(); } public void visit(ElementC element){ element.operationC(); } } Public class VisitorDemo{ public static void main(String[] args){ IElement[] list = {new ElementA(), new ElementB(), new ElementC()}; IVisitor visitor = new MyVisitor(); for(int i = 0; i < list.length; i++){ list[i].accept(visitor); } } }