23 design modes (16) java visitor mode and 23 design modes

Source: Internet
Author: User

23 design modes (16) java visitor mode and 23 design modes

23 design patterns Article 16th: java visitor Mode

Definition: encapsulate some 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.

Type: behavior mode

Class diagram:


The visitor pattern may be the most complex pattern in the behavior pattern, but this cannot be the reason for us not to grasp it.

Let's take a simple example. The Code is as follows:

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 ();}}

Let's take A look at the differences between Methods method1 and method2 in Class A. The method method1 is very simple, that is, to print 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

After understanding this example, we understand 90% of the visitor mode. In this example, Class B is A visitor for Class. However, this example is not all about the visitor mode. Although it is intuitive, it has poor scalability. Let's take a look at the general implementation of the visitor mode. We can see it through the class diagram, the visitor mode mainly includes the following roles:

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 is its own business logic, and the other is the type of visitors allowed to access.
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.

Universal Code Implementation of visitor Mode

Abstract class Element {public abstract void accept (IVisitor visitor); public abstract void doSomething ();} interface IVisitor {public void visit (ConcreteElement1 el1 ); public void visit (ConcreteElement2 el2);} 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) ;}} class Visitor implements IVisitor {public void visit (ConcreteElement1 el1) {tenant ();} public void visit (ConcreteElement2 el2) {el2.doSomething ();}} 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 ;}} public class Client {public static void main (String [] args) {List <Element> list = ObjectStruture. getList (); for (Element e: list) {e. accept (new Visitor ());}}}

Advantages of visitor Mode

In line with the single principle of responsibility: in any scenario applicable to the visitor mode, the operations in the element class that need to be encapsulated in the visitor must be operations that are not closely related to the element class and are easy to change, on the one hand, the visitor mode conforms to the single responsibility principle. On the other hand, because encapsulated operations are usually changeable, when a change occurs, the element class itself can be kept unchanged, implement expansion of the change part.
Good scalability: element classes can expand different operations by accepting different visitors.

Applicable scenarios of visitor Mode

If 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.
However, the visitor pattern is not so perfect, and it also has a fatal defect: 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.

Summary

As GoF, author of design patterns, describes the visitor mode: In most cases, you need to use the visitor mode, but once you need to use it, then you really need it. Of course, this is only for the real Daniel. In reality (at least in my environment), many people tend to indulge in design patterns. When they use a design pattern, I never seriously consider whether the mode I use is suitable for this scenario. Instead, I often just want to demonstrate my ability to control object-oriented design. This kind of psychology often leads to misuse of the Design Pattern During programming. Therefore, when learning the design model, you must understand the applicability of the model. You must use a mode because you understand its advantages. If you do not use a mode, you need to understand its disadvantages. Instead, you cannot use a mode because you do not understand its disadvantages, A mode is not used because you do not understand its advantages.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.