Visitor mode in Java and Mode

Source: Internet
Author: User
ArticleDirectory
    • Source code

Dr. Yan Hong's book "Java and patterns" describes the visitor (visitor) mode in this way:

The visitor mode is the behavior mode of objects. The visitor mode aims to encapsulate operations that are applied to certain data structure elements. Once these operations need to be modified, the data structure that accepts the operation can remain unchanged.

Assignment Concept

When a variable is declared, the type is called the static type of the variable. Some people call the static type apparent type ); the actual type of the object referenced by the variable is also called the actual type of the variable (actual type ). For example:

 
List list =Null; List=NewArraylist ();

Declares a variable list. Its static type (also called explicit type) is list, and its actual type is arraylist.

The method selected based on the object type is the dispatch (dispatch), which is divided into two types:Static assignmentAndDynamic Allocation.

Static dispatch)Occurs during the compilation period, and the assignment occurs based on static type information. Static distribution is no stranger to us. Method overloading means static distribution.

Dynamic dispatch)In the running period, a method is dynamically assigned and replaced.

Static assignment

JAVA supports static allocation through method overloading. The story of Mozi riding is used as an example. Mozi can ride a white horse or a dark horse. The Mozi and Whitehorse, dark horse, and horse classes are shown as follows:

In this system, Mozi is represented by the Mozi class.

 Public   Class  Mozi {  Public   Void  Ride (horse H) {system. Out. println ( "Horse riding" );}  Public   Void  Ride (Whitehorse Wh) {system. Out. println ( "Riding White Horse");}  Public   Void  Ride (Blackhorse BH) {system. Out. println ( "Riding a dark horse" );}  Public   Static   Void  Main (string [] ARGs) {Horse wh = New  Whitehorse (); horse BH = New  Blackhorse (); Mozi = New Mozi (); Mozi. Ride (Wh); Mozi. Ride (BH );}} 

Obviously, the ride () method of the Mozi class is composed of three methods that are overloaded. These three methods accept parameters of the following types: Horse (Horse), White Horse (Whitehorse), and black horse (Blackhorse.

Then,ProgramWhat results will be printed? The result is that the program prints the same two "horse riding" lines ". In other words, Mozi finds that he is riding a horse.

Why? The two calls to the ride () method pass in different parameters, that is, WH and BH. Although they have different real types, their static types are the same, all of which are horse types.

The assignment of the overload method is based on the static type, and the assignment process is completed during compilation.

Dynamic Allocation

JAVA supports dynamic dispatch through method rewriting. Using the story of Grazing horses as an example,CodeAs follows:

 
Public ClassHorse {Public VoidEat () {system. Out. println ("Horse grazing");}}
Public ClassBlackhorseExtendsHorse {@ overridePublic VoidEat () {system. Out. println ("Dark horse grazing");}}
 
Public ClassClient {Public Static VoidMain (string [] ARGs) {Horse H=NewBlackhorse (); H. Eat ();}}

The static type of variable H is horse, while the actual type is Blackhorse. If the Eat () method in the last row above calls the Eat () method of the Blackhorse class, the printed above is "dark horse grazing". On the contrary, if the Eat () method above is () the method calls the Eat () method of the horse class, and the print is "horse grazing ".

Therefore, the core of the problem is that the Java compiler does not always know which code will be executed during compilation, because the compiler only knows the static type of the object and does not know the actual type of the object; the call of a method is based on the actual type of the object, rather than the static type. In this way, the Eat () method in the last row above calls the Eat () method of the Blackhorse class and prints the "dark horse grazing ".

Assigned type

The object to which a method belongs is called the method receiver. The method receiver and the method parameters are collectively referred to as the number of methods. For example, the test class in the following example

 
Public ClassTest {Public VoidPrint (string Str) {system. Out. println (STR );}}

In the above class, the print () method belongs to the test object, so its receiver is the test object. The print () method has a parameter STR, which is of the string type.

You can divide object-oriented languages into single-assignment languages (uni-dispatch) and Multi-assignment languages (Multi-dispatch) based on how many types of data can be distributed ). A single assignment language selects a method based on the type of a single parcel. Multiple assignment languages select a method based on the type of more than one parcel.

C ++ and Java are both single-assignment languages. Examples of Multi-assignment languages include Clos and Cecil. According to this distinction, Java isDynamic Single-assignment LanguageBecause the dynamic distribution of this language only takes into account the type of the method receiver andStatic multi-assignment LanguageBecause the assignment of overload methods in this language takes into account the type of the method receiver and the types of all parameters of the method.

In a language that supports dynamic single assignment, there are two conditions that determine which operation a request will call: first, the request name, but the real type of the recipient. Single dispatch limits the method selection process so that only one parcel can be considered. This parcel is usually the method receiver. In Java, if an operation is performed on an object of unknown type, the actual type test of this object will only happen once, which is the feature of dynamic single assignment.

Double dispatch

One method decides to execute different code based on the two types of data sets, which is "Double dispatch ". The Java language does not support dynamic multi-distribution, which means that Java does not support dynamic dual-distribution. However, by using the design pattern, you can also implement dynamic dual-allocation in the Java language.

In Java, two methods can be called to achieve the goal of two distributions. The class diagram is as follows:

In the figure, there are two objects: West on the left and east on the right. Now, the West object first calls the goeast () method of the East object and passes it in. When the East object is called, the system immediately knows who the caller is based on the input parameters, and calls the gowest () method of the "Caller" object in turn. The control of the program is rotated to two objects through two calls. The time sequence is shown as follows:

In this way, two method calls occur, and the control of the program is transmitted to the east object by two objects like passing a pass. Then, the West object is returned to the east object.

However, if you pass back the ball, the problem of dual allocation cannot be solved. The key is how to use these two calls and the dynamic single dispatch function of the Java language, so that two single distributions can be triggered during the transfer process.

Dynamic Single Assignment occurs when the child class overrides the parent class method in Java. In other words, both West and East must be in their own type level structure, as shown in:

Source code

West class

 
Public Abstract ClassWest {Public Abstract VoidGowest1 (subeast1 East );Public Abstract VoidGowest2 (subeast2 East );}

Subwest1 class

Public ClassSubwest1ExtendsWest {@ overridePublic VoidGowest1 (subeast1 East) {system. Out. println ("Subwest1 +" +East. myname1 ();} @ overridePublic VoidGowest2 (subeast2 East) {system. Out. println ("Subwest1 +" +East. myname2 ());}}

Subwest2 class

Public ClassSubwest2ExtendsWest {@ overridePublic VoidGowest1 (subeast1 East) {system. Out. println ("Subwest2 +" +East. myname1 ();} @ overridePublic VoidGowest2 (subeast2 East) {system. Out. println ("Subwest2 +" +East. myname2 ());}}

East class

Public Abstract ClassEast {Public Abstract VoidGoeast (West );}

Subeast1 class

Public ClassSubeast1ExtendsEast {@ overridePublic VoidGoeast (West) {west. gowest1 (This);}PublicString myname1 (){Return"Subeast1";}}

Subeast2 class

Public ClassSubeast2ExtendsEast {@ overridePublic VoidGoeast (West) {west. gowest2 (This);}PublicString myname2 (){Return"Subeast2";}}

Client type

  Public   class   client {  Public   static   void   main (string [] ARGs) {  //   combination 1  East =  New   subeast1 (); West  =  New   subwest1 (); East. goeast (West);  ///   combination 2  East =  New   subeast1 (); West  =  New   subwest2 (); East. goeast (West) ;}} 

The running result is as follows:

Subwest1 + subeast1
Subwest2 + subeast1

 

When the system is running, it first creates the subwest1 and subeast1 objects, then the client calls the goeast () method of subeast1, and passes in the subwest1 object.Because the subeast1 object overrides the goeast () method of its super class east, a dynamic single dispatch occurs at this time.. When the subeast1 object is called, it will get the subwest1 object from the parameter, so it immediately calls the gowest1 () method of this object and passes it in. Because the subeast1 object has the right to select which object to call, a dynamic method assignment is performed at this time.

At this time, the subwest1 object obtains the subeast1 object. By calling the myname1 () method of this object, you can print your own name and the name of the subeast object. The sequence diagram is as follows:

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.