Java visitor Mode

Source: Internet
Author: User

I. Introduction

For a completed class hierarchy in the system, we have provided it with interfaces that meet the requirements. But what should we do in the face of new demands? If this is one of the few changes, and you don't have to modify the entire class hierarchy for a requirement adjustment, it may be a good idea to modify the existing class hierarchy directly.

But what we often encounter is: such changes may happen constantly; more importantly, any change in requirements may require you to modify the entire class hierarchy ....... Similar operations are distributed in different classes, which is not a good phenomenon. We need to reconstruct this structure.

The visitor mode may be your preferred choice.

   Ii. Definition and Structure

Visitor mode, as the name implies, with this mode, you can add additional "visitors" without modifying the existing program structure to improve the existing code functions.

The design pattern book defines the visitor pattern as an operation that acts on each element of an object structure. It allows you to define new operations that act on these elements without changing the classes of each element. From the definition, we can see that the structure object is a required condition for using the visitor mode, and this structure object must have a method to traverse its own objects. This is similar to the collection concept in java.

The structure of the visitor mode is as follows:

1) Visitor role (Visitor): declares an access operation interface for the specific element role in the object structure. The name and parameters of this operation interface identify the specific element role that sends an access request to a specific visitor. In this way, the visitor can directly access the element through a specific interface of the element role.

2) A specific Visitor role (Concrete Visitor): implements each operation declared by the Visitor role (Visitor.

3) Element: defines an Accept operation, which takes a visitor as the parameter.

4) specific Element (Concrete Element): implements the Accept operation provided by the Element role.

5) Object Structure Role: This is a required role in the visitor mode. It must have the following features: it can enumerate its elements; it can provide a high-level interface to allow the visitor to access its elements; it can be a combination (combination mode) or a set, such as a list or an unordered set.

You can see the structure of the visitor pattern in a class chart.


This is like the imaginary in the introduction. What should we do to make the visitor mode run? First, we need to add the accept method in the original class hierarchy. Then, put the classes in the class hierarchy into an object structure. In this way, create a visitor role ......

   Iii. Example

My experience is really poor, and I failed to find examples of the visitor mode in practical application. I had to use the teaching code in Thinking in Patterns with java. I made some modifications.

Import java. util .*;
Import junit. framework .*;

// Visitor role

Interface Visitor {
Void visit (Gladiolus g );
Void visit (Runuculus r );
Void visit (Chrysanthemum c );
}

// The Flower hierarchy cannot be changed:
// Element role

Interface Flower {
Void accept (Visitor v );
}

// The following three specific element roles

Class Gladiolus implements Flower {
Public void accept (Visitor v) {v. visit (this );}
}

Class Runuculus implements Flower {
Public void accept (Visitor v) {v. visit (this );}
}

Class Chrysanthemum implements Flower {
Public void accept (Visitor v) {v. visit (this );}
}

// Add the ability to produce a string:
// Specific visitor role

Class StringVal implements Visitor {
String s;
Public String toString () {return s ;}
Public void visit (Gladiolus g ){
S = "Gladiolus ";
}

Public void visit (Runuculus r ){
S = "Runuculus ";
}

Public void visit (Chrysanthemum c ){
S = "Chrysanthemum ";
}
}

// Add the ability to do "Bee" activities:
// Another visitor role

Class Bee implements Visitor {
Public void visit (Gladiolus g ){
System. out. println ("Bee and Gladiolus ");
}

Public void visit (Runuculus r ){
System. out. println ("Bee and Runuculus ");
}

Public void visit (Chrysanthemum c ){
System. out. println ("Bee and Chrysanthemum ");
}
}

// This is an object generator.
// This is not a complete object structure. Here we only simulate elements in the object structure.

Class FlowerGenerator {
Private static Random rand = new Random ();
Public static Flower newFlower (){
Switch (rand. nextInt (3 )){
Default:
Case 0: return new Gladiolus ();
Case 1: return new Runuculus ();
Case 2: return new Chrysanthemum ();
}
}
}

// Customer Test Program

Public class BeeAndFlowers extends TestCase {

/*
Here you can see the process of visitor mode execution:
First, obtain a specific visitor role on the client.
Traverse object structure
Call the accept method for each element to pass in a specific visitor role
This completes the entire process.
*/
// The object structure role is assembled here

List flowers = new ArrayList ();
Public BeeAndFlowers (){
For (int I = 0; I <10; I ++)
Flowers. add (FlowerGenerator. newFlower ());
}

Visitor sval;
Public void test (){
// It's almost as if I had a function
// Produce a Flower string representation:
// You can modify this part to use another specific visitor role.

Sval = new StringVal ();
Iterator it = flowers. iterator ();
While (it. hasNext ()){
(Flower) it. next (). accept (sval );
System. out. println (sval );
}
}

Public static void main (String args []) {
Junit. textui. TestRunner. run (BeeAndFlowers. class );
}

}

   Iv. Dual allocation

By the way, have you realized the implementation of double dispatch in the above example?

First, pass the visitor mode as a parameter in the customer program to the specific element role (highlighted ). This completes a dispatch.

After entering a specific element role, the specific element angular tones are used as the visitor method in the specific visitor mode of the parameter, and the user (this) is passed as the parameter. The visitor mode is used to select a method based on different parameters (as shown in the highlighted area ). This completes the second assignment.

   V. Advantages and Disadvantages and Applicability

Let's take a look at whether the use of the visitor mode can avoid the pain points in the introduction. After the visitor mode is used, you only need to implement a specific visitor role to add new operations to the original class hierarchy without modifying the entire class hierarchy. In addition, this meets the requirements of the "open and closed principle. In addition, each specific visitor role corresponds to a related operation. Therefore, if the demand for an operation changes, you only need to modify a specific visitor role without changing the entire class level.

It seems that the visitor mode can solve some of our problems.

In addition, the visitor mode provides a "visitor" layer for our system, so we can add some additional operations for element roles to the visitor.

However, the principle of "open and closed" is always one-sided. If the class hierarchy in the system changes, what will happen to the visitor mode? You must modify the visitor role and each specific visitor role ......

It seems that the visitor role is not suitable for situations where the specific element role often changes. In addition, to perform operations related to the element role, the element role must expose its internal attributes. in java, other objects can be accessed. This damages the encapsulation of element roles. In addition, in the visitor mode, the information that can be transmitted between elements and visitors is limited, which often limits the use of the visitor mode.

The book "design patterns" shows the application of visitor patterns:

1) An object structure contains many class objects with different interfaces. You want to perform operations on these objects dependent on their specific classes.

2) You need to perform many different and unrelated operations on the objects in an object structure, and you want to avoid causing these operations to "pollute" the classes of these objects. Visitor allows you to define related operations in a class.

3) when the object structure is shared by many applications, use the Visitor mode to allow each application to only include the operations needed.

4) classes that define the object structure are rarely changed, but new operations are often needed in this structure. Changing the object structure class requires redefining the interfaces for all visitors, which may be costly. If the object structure class changes frequently, it may be better to define these operations in these classes.

Can you understand it well?

   Vi. Summary

This is a clever and complex model with harsh conditions. When there is a fixed data structure (such as the class hierarchy above) in the system and there are different behaviors, then the visitor Module

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.