Visitor mode in Design Mode
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:
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + yr7A/placement = "brush: java;"> public interface Vistor {public abstract void partition (ConcreteElementA concreteElementA); public abstract void partition (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 Elements = new ArrayList (); 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