The visitor pattern for Java design patterns

Source: Internet
Author: User

This article continues23 Different design modesthe visitor mode of the series.

definitionencapsulates certain operations that act on elements of a data structure, and it can define new operations that act on these elements without altering 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) {          a.method1 ();      }  
Take a look at the difference between method Method1 and method Method2 in Class A, the method method1 simple, is to print out a "I am a"; the method method2 slightly more complex, uses Class B as a parameter, and invokes the Showa method of Class B. Then look at the Showa method of Class B, the Showa method uses Class A as a parameter, and then call the Method1 method of Class A, you can see that the Method2 method around to go around, nothing is called a method1 method of its own, it should also run the result should be "I am a", After the analysis, let's run through the two methods and look at the results of the operation:

public class Test {public      static void Main (string[] args) {          A A = new A ();          A.method1 ();          A.METHOD2 (New B ());      }  }  

The result of the operation is:

I'm a.
I'm a.

rolein the example, for Class A, Class B is a visitor. Abstract Visitor:An abstract class or interface that declares which elements a visitor can access, specifically the parameters in the visit method that define which objects are accessible to the program. Visitor:implements the method that is declared by an abstract visitor, which affects what the visitor does and does when it accesses a class. abstract Element class:interface or abstract class that declares which type of visitor access to accept is defined by the parameters in the Accept method. Abstract elements generally have two types of methods, part of which is business logic of its own, the other is What types of visitors are allowed to receiveto access. element class:implementing the Accept method declared by the abstract element class, usually visitor.visit (this), has basically formed a stereotype. Structure object:a container for an element that typically contains a container that accommodates multiple different classes and interfaces, such as list, Set, map, and so on, is rarely abstracted from this role in the 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);    
Visitors
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 (+);              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 ());          }      }  

Advantagesin accordance with the principle of single responsibility: in any scenario where the visitor pattern is applicable, the action that needs to be encapsulated in the visitor in the element class must be an operation that is not related to the element class itself and is variable, while using the visitor pattern on the one hand conforms to the principle of single responsibility, Because the encapsulated operation is usually variable, it is possible to extend the variation without changing the element class itself, even when the change occurs. Good Extensibility: element classes can be extended to different operations by accepting different audiences.
DisadvantagesAdding new element classes is more difficult. The code of the visitor pattern can see that in the visitor class, each element class has its corresponding processing method, that is, each additional element class needs to modify the visitor Class (also includes the visitor class subclass or the implementation Class), the modification is quite troublesome. In other words, the visitor pattern should be used with caution in cases where the number of element classes is uncertain. Therefore, the visitor pattern is suitable for the reconstruction of the existing function, for example, the basic function of a project has been determined, the element class data has been basically determined to not change, will change only the relevant operations within these elements, we can use the visitor pattern to reconstruct the original code again, so that, You can modify the original functionality without modifying the individual element classes.
Applicable ScenariosIf there are some operations in an object that are irrelevant (or weaker) to this object, you can use the visitor pattern to encapsulate these actions to the visitor in order to avoid polluting the object. If there is a similar operation in a set of objects, you can encapsulate the repeated actions in the visitor in order to avoid the occurrence of a large number of duplicated code.
More Design Patterns:23 design Mode series

jason0539

Blog: http://blog.csdn.net/jason0539 (reprint please indicate the source)

Recommended scan code pay attention to the public number, the different things


The visitor pattern for Java design patterns

Related Article

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.