Visitor pattern: Represents an element action that acts on an object structure. It allows you to define new operations that act on these elements without changing the class of each element.
First, define a visitor abstract class, declaring a visit operation for each specific class
publicabstractclass Visitor { publicabstractvoidvisitConcreteElementA(ConcreteElementA elementA); publicabstractvoidvisitConcreteElementB(ConcreteElementB elementB);}
Then define the specific classes that inherit the visitor
Public class ConcreteVisitor1 extends Visitor{ @Override Public void Visitconcreteelementa(Concreteelementa Elementa) {System.out.println (Elementa.getclass (). GetName () +"Access"+ This. GetClass (). GetName ()); }@Override Public void VISITCONCRETEELEMENTB(Concreteelementb ELEMENTB) {System.out.println (Elementb.getclass (). GetName () +"Access"+ This. GetClass (). GetName ()); }} Public class ConcreteVisitor2 extends Visitor{ @Override Public void Visitconcreteelementa(Concreteelementa Elementa) {System.out.println (Elementa.getclass (). GetName () +"Access"+ This. GetClass (). GetName ()); }@Override Public void VISITCONCRETEELEMENTB(Concreteelementb ELEMENTB) {System.out.println (Elementb.getclass (). GetName () +"Access"+ This. GetClass (). GetName ()); }}
Then define an element abstract class that defines an accept method
publicabstractclass Element { publicabstractvoidaccept(Visitor visitor);}
Then define the specific class that inherits the element
Public class concreteelementa extends Element{ @Override Public void Accept(Visitor Visitor) {Visitor.visitconcreteelementa ( This); } Public void Operationa(){ }} Public class concreteelementb extends Element{ @Override Public void Accept(Visitor Visitor) {VISITOR.VISITCONCRETEELEMENTB ( This); } Public void operationb(){ }}
Then define a Objectstructure class to enumerate its elements.
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 (Visitor Visitor) {iterator<element> iterator=elements.iterator (); while (Iterator.hasnext ()) {Element element=iterator.next (); Element.accept (visitor); } }}
Client code
publicstaticvoidmain(String[] args) { //访问者模式 ObjectStructure oStructure=new ObjectStructure(); oStructure.attach(new ConcreteElementA()); oStructure.attach(new ConcreteElementB()); ConcreteVisitor1 visitor1=new ConcreteVisitor1(); ConcreteVisitor2 visitor2=new ConcreteVisitor2(); oStructure.accept(visitor1); oStructure.accept(visitor2); }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Visitor mode of design mode (note)