publicabstractclassElement{publicabstractvoiddoSomething();publicabstractvoidaccept(IVisitorvisitor);// 依赖访问者接口}// 具体元素类1publicclassConcreteElement1extendsElement{@OverridepublicvoiddoSomething(){// 业务逻辑放这里System.out.println(getClass().getSimpleName()+" do something.");}@Overridepublicvoidaccept(IVisitorvisitor){visitor.visit(this);// 将自身传入来访者}}publicclassConcreteElement2extendsElement{@OverridepublicvoiddoSomething(){System.out.println(getClass().getSimpleName()+" do something.");}@Overridepublicvoidaccept(IVisitorvisitor){visitor.visit(this);// 将自身传入来访者}}
Visitorvisitor=newVisitor();for(inti=0;i<4;i++){Elementel=ObjectStructure.createElement();el.accept(visitor);}/* output ConcreteElement1 do something. ConcreteElement2 do something. ConcreteElement2 do something. ConcreteElement2 do something. */