Definition: indicates an operation that acts on each element in an object structure. It allows you to define new operations that act on these elements without changing the classes of each element.
Structure:
Sample Code:
public interface Vistor {public abstract void vistorConcreteElementA(ConcreteElementA concreteElementA);public abstract void vistorConcreteElementB(ConcreteElementB concreteElementB);}public class ConcreteVisitor1 implements Vistor {@Overridepublic void vistorConcreteElementA(ConcreteElementA concreteElementA) {// TODO Auto-generated method stubSystem.out.println(concreteElementA.getClass().getName() + " " + this.getClass().getName());}@Overridepublic void vistorConcreteElementB(ConcreteElementB concreteElementB) {// TODO Auto-generated method stubSystem.out.println(concreteElementB.getClass().getName() + " " + this.getClass().getName());}}public class ConcreteVistor2 implements Vistor {@Overridepublic void vistorConcreteElementA(ConcreteElementA concreteElementA) {// TODO Auto-generated method stubSystem.out.println(concreteElementA.getClass().getName() + " " + this.getClass().getName());}@Overridepublic void vistorConcreteElementB(ConcreteElementB concreteElementB) {// TODO Auto-generated method stubSystem.out.println(concreteElementB.getClass().getName() + " " + this.getClass().getName());}}public abstract class Element {public abstract void accept(Vistor vistor);}public class ConcreteElementA extends Element {@Overridepublic void accept(Vistor vistor) {// TODO Auto-generated method stubvistor.vistorConcreteElementA(this);}public void OperationA() {}}public class ConcreteElementB extends Element{@Overridepublic void accept(Vistor vistor) {// TODO Auto-generated method stubvistor.vistorConcreteElementB(this);}public void OperationB() {}}public class ObjectStructure {private List<Element> elements = new ArrayList<Element>();public void attach(Element element) {elements.add(element);}public void detach(Element element) {elements.remove(element);}public void accept(Vistor vistor) {for (Element e: elements) {e.accept(vistor);}}}The client code is as follows:
public class Client {public static void main(String[] args) {ObjectStructure o = new ObjectStructure();o.attach(new ConcreteElementA());o.attach(new ConcreteElementB());ConcreteVisitor1 v1 = new ConcreteVisitor1();ConcreteVistor2 v2 = new ConcreteVistor2();o.accept(v1);o.accept(v2);}}
Output result:
Strategy. vistor. concreteelementa strategy. vistor. concretevisitor1
Strategy. vistor. concreteelementb strategy. vistor. concretevisitor1
Strategy. vistor. concreteelementa strategy. vistor. concretevistor2
Strategy. vistor. concreteelementbstrategy. vistor. concretevistor2
Visitor mode in Design Mode