Visitor mode in Java design mode and visitor mode in java Design Mode

Source: Internet
Author: User

Visitor mode in Java design mode and visitor mode in java Design Mode
This article continues with the visitor mode of the 23 design patterns series.

Define encapsulate certain operations that act on each element in a data structure. It can define new operations that act on these elements without changing the data structure.

Class A {public void method1 () {System. out. println ("I am A");} public void method2 (B B) {B. showA (this) ;}} class B {public void showA (A a) {. method1 ();}}
In Class A, let's take A look at the difference between method method1 and method method2. The method method1 is very simple, that is, to print out A sentence "I am A". The method method2 is A little more complex, use Class B as the parameter and call the showA method of Class B. Let's take A look at the showA method of class B. the showA method uses Class A as the parameter and then calls the method1 method of Class A. We can see that the method2 method is bypassed, it is nothing more than calling its own method1 method. Its running result should also be "I am A". After analysis, let's run the two methods, take a look at the running results:

public class Test {      public static void main(String[] args){          A a = new A();          a.method1();          a.method2(new B());      }  }  

The running result is:

I am
I am

In this example, for Class A, Class B is A visitor. Abstract Visitor:An abstract class or interface that declares what elements a visitor can access. Specifically, the parameters in the visit method in the program define which objects can be accessed. Visitor:Implement the method declared by the abstract visitor, which affects what the Visitor should do and what to do after accessing a class. Abstract element class:The interface or abstract class declares the access type of the visitor, which is defined by the parameters in the accept method in the program. Abstract elements generally have two types of methods, one being Business LogicIn addition Visitors allowed to receive. Element class:The accept method declared to implement the abstract element class is usually visitor. visit (this), which basically forms a pattern. Structure object:An element container generally contains a container that contains multiple different classes and interfaces, such as List, Set, and Map. This role is rarely abstracted from a project.
Abstract element class
abstract class Element {      public abstract void accept(IVisitor visitor);      public abstract void doSomething();  }  
Element class
Class ConcreteElement1 extends Element {public void doSomething () {System. out. println ("this is element 1");} public void accept (IVisitor visitor) {visitor. visit (this) ;}} class ConcreteElement2 extends Element {public void doSomething () {System. out. println ("this is element 2");} public void accept (IVisitor visitor) {visitor. visit (this );}}
Abstract visitor
interface IVisitor {      public void visit(ConcreteElement1 el1);      public void visit(ConcreteElement2 el2);  }  
Visitor
class Visitor implements IVisitor {        public void visit(ConcreteElement1 el1) {          el1.doSomething();      }            public void visit(ConcreteElement2 el2) {          el2.doSomething();      }  } 
Structure object
class ObjectStruture {      public static List<Element> getList(){          List<Element> list = new ArrayList<Element>();          Random ran = new Random();          for(int i=0; i<10; i++){              int a = ran.nextInt(100);              if(a>50){                  list.add(new ConcreteElement1());              }else{                  list.add(new ConcreteElement2());              }          }          return list;      }  }  
Client
public class Client {      public static void main(String[] args){          List<Element> list = ObjectStruture.getList();          for(Element e: list){              e.accept(new Visitor());          }      }  } 

Advantages Compliant with the single responsibility principle:In the scenario where the visitor mode is applied, the operations that the element class needs to encapsulate in the visitor must have little to do with the element class itself and are easy to change. The visitor mode meets the single responsibility principle on the one hand, on the other hand, because encapsulated operations are usually changeable, you can expand the changed part without changing the element class itself. Good scalability:Element classes can be extended for different operations by accepting different visitors.
Disadvantages it is difficult to add new element classes. The code in the visitor mode shows that in the visitor class, each element class has its corresponding processing method, that is, every time you add an element class, you need to modify the visitor class (including the subclass or implementation class of the visitor class), which is quite troublesome to modify. That is to say, when the number of element classes is uncertain, the visitor mode should be used with caution. Therefore, the visitor mode is suitable for restructuring existing functions. For example, the basic functions of a project have been determined, and the data of element classes has been basically determined and will not change, only related operations in these elements will change. At this time, we can use the visitor mode to refactor the original code. As a result, you can modify the original functions without modifying each element class.
Applicable scenariosIf an object has some operations unrelated to the object (or the relationship is weak), to avoid these operations polluting the object, the visitor mode can be used to encapsulate these operations into the visitor. If there are similar operations in a group of objects, to avoid a large number of repeated code, you can also encapsulate these repeated operations into the visitor.
More design patterns: 23 Design Patterns

Author: jason0539

Blog: http://blog.csdn.net/jason0539 (reprinted please explain the source)

We recommend that you scan the QR code to follow the public account and look at different things.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.