Java design Pattern (iii) Visitor (interview) mode and multi-allocation scenario application

Source: Internet
Author: User

Basic Concept Visitor
    • Encapsulates some operations for each element in the data structure, and different operations can be implemented with the help of a new visitor. Reduced coupling between operations
    • Visitors are able to decouple data structures and operations , making it unnecessary to change data structures or to alter the original operations, and to define new visitor when run-time ( easy to expand in operation) )
Role Division in the pattern
    • Visitor: Abstract accessor, in the overloaded visit function, declares the object that the caller can access .
    • Concrete Visitor: Implementing an interview with an operator for a detailed element
    • element: An abstract element that declares the type of the person who has access to the permission of the type element (usually an abstract type). Provides permissions for overloaded accept functions
    • Concrete Element: Implementation of the Accept method, basically templated visitor.visit (this)
    • Object Structure: Accommodating multiple types may be different. An interface or a collection of different elements.
For example, the realization of visitor is a simple example that shows the most basic and humble visitor

Since the spring season. We give a sample of the screening of resumes, all of which are written by undergraduates and junior college students. Also has the master's degree, the high profession ah ... For simplicity, take the first two. The candidate's CV is implemented as an element such as the following:

AbstractClass Student {//provides functions for basic operation of data fields    PrivateString name;PrivateString University;PrivateString rating;//Let the specified visitor get permission to manipulate the object     Public Abstract void Accept(Visitor Visitor); PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } PublicStringgetuniversity() {returnUniversity } Public void setuniversity(String University) { This. University = University; } PublicStringgetrating() {returnRating } Public void setrating(String rating) { This. rating = rating; }}class Bachelor extends student{@Override     Public void Accept(Visitor Visitor) {Visitor.visit ( This); }}class College extends student{@Override     Public void Accept(Visitor Visitor) {Visitor.visit ( This); }}

Since we have only defined two types of students, the interface provides access to two types of element

interface Visitor{    publicvoidvisit ( Bachelor bachelor );    publicvoidvisit ( College college );}

First of all, we'll look at your resume, and we'll need a showvisitor:

Class Showvisitor implements Visitor {@Override     Public void Visit(Bachelor Bachelor) {System.out.println ("A bachelor\n");//todo may have some specific operations, we omit it for simplicity         This. Printmessage (Bachelor); }@Override     Public void Visit(College College) {System.out.println ("A college student!\n");//todo Ibid .         This. Printmessage (college); } Public void Printmessage(Student Student) {System.out.println ("Name:"+ student.getname () +"\ n"+"University:"+ student.getuniversity () +"\ n"+"Rating:"+ student.getrating () +"\ n"); }}

To test, we first construct a data set. That is, the corresponding objectstructure in the role, for the sake of simplicity, we use ArrayList directly.

 Public  class visitoreg {     Public Static void Main(String [] args) {arraylist<student> list =NewArraylist<student> (); Bachelor Bachelor =NewBachelor (); Bachelor.setname ("Llin"); Bachelor.setrating (" the"); Bachelor.setuniversity ("Tianjin University"); College College =NewCollege (); College.setuniversity ("Tianjin College"); College.setrating ("1"); College.setname ("Dalinge");        List.add (Bachelor);        List.add (college); Visitor Visitor =NewShowvisitor (); for(Student student:list)        {student.accept (visitor); }    }}

So it seems like there's no way to see the benefits of the interview model!!! And good trouble, but because you have the data structure and the operation of separate (decoupling ), so when I want to join the new operation, there is no need to change the original class, just need to implement a visitor again.

So, let's go back to this example. So many people sign up, so how many undergraduates (assuming the number is enough, may be directly lazy to interview undergraduates only),-_-the evil of such HR, so we need a statistical visitor:

Class Sumvisitor implements visitor{Private intTotalbachelor; Sumvisitor () {Super(); Totalbachelor =0; }@Override     Public void Visit(Bachelor Bachelor)    {totalbachelor++; }@Override     Public void Visit(College College) {    } Public int Gettotal_bachelor() {returnTotalbachelor; }} Public  class visitoreg {     Public Static void Main(String [] args) {arraylist<student> list =NewArraylist<student> (); Bachelor Bachelor =NewBachelor (); Bachelor.setname ("Llin"); Bachelor.setrating (" the"); Bachelor.setuniversity ("Tianjin University"); College College =NewCollege (); College.setuniversity ("Tianjin College"); College.setrating ("1"); College.setname ("Dalinge");        List.add (Bachelor);        List.add (college); Visitor Visitor =NewShowvisitor (); Visitor Visitor1 =NewSumvisitor (); for(Student student:list)            {student.accept (visitor);        Student.accept (Visitor1); } System.out.println ("The total sum of bachelors:"+ ((sumvisitor) visitor1). Gettotal_bachelor ()); }}

Meet the requirements. But did not change a line of code, happy!

Visitor application Scenarios There must be doubt: visitor and iterator differences:
    • Visitor is able to access different objects (just need to define the appropriate accept in element), but iterator can only interview the same object. At least we have the same interface.
    • Iterator is not dependent on the detailed implementation , and visitor is dependent on the detailed implementation , because visitor will be based on the detailed access to the object to take appropriate action, and iterator is only based on the same interface generalization implementation.
    • The data structure of the iterator is not separated from the operation and the information. So the expansion function needs to change, violates the opening and shutting principle and the single duty principle .

      But because the visitors rely on detailed implementations, rather than relying on abstraction. So It violates the principle of dependency inversion.

Application scenarios with strengths and weaknesses in mind
    • Conforms to the principle of single responsibility. Functionality has good extensibility, but because the dependency detail implementation violates the detailed implementation, so for the class changes brought trouble.
    • has a good extensibility. Just need to implement new visitor to meet new access requirements.

      Due to the separation of data and operations, it is prevented from adding new operations to contaminate the original data structure.

In comprehensive

An interview is a centralized, structured pattern that is particularly suitable for projects that are used for large-scale refactoring. The requirements at this stage have been very clear and the functional points of the original system have been understood. Through the interview mode can be very easy to comb some functions to achieve the goal of centralized function

Double allocation first describes the following single dispatch

Single Dispatch : An operation is determined by the name of the requestor and the number of participants received, and is statically bound and dynamically bound in Java, each implemented by overloading and overriding.


Double dispatch : A double allocation means that the operation being run depends on the kind of request and the type of receiver .

is corresponding to the interview mode .

Javac is used to construct, optimize and parse the syntax tree in visitor mode (grammar, semantic analysis phase)

Java design Pattern (iii) Visitor (interview) mode and multi-allocation scenario application

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.