Design Pattern (18) --- Visitor pattern

Source: Internet
Author: User

Design Pattern (18) --- Visitor pattern

Definition: Encapsulate 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.

Normal Mode


Visitor ---- abstract Visitor
-- "Abstract class or interface that declares that visitors can access those elements. Specifically, the visit parameter in the program defines that objects can be accessed.
ConcreteVisotor --- abstract element
--- | It affects what the Visitor should do and what to do after accessing the class.
Element --- abstract Element
-- | Interface or abstract class that declares which type of access is accepted. The program uses the Parameter definition in the accept method.
ConcreteElement --- specific elements
-- | Implements the accept method, usually visitor. visit (this), which basically forms a mode.
ObjectStruture --- structure object

-- | Element setter, which is generally used in containers with different classes and interfaces, such as List, Set, and Map. In projects, this role is rarely abstracted.

Public class VisitorTest {public static void main (String [] args) {// generates 10 specific element objects for (int I = 0; I <10; I ++) {Element e = ObjectStruture. createElement (); // receives visitor access e. accept (new ConcreteVisitor () ;}}/*** abstract element class * In addition to its own business logic, * defines which type of visitors can access. * @ Author admin **/abstract class Element {// execute its own business logic public abstract void doSomenthing (); // define public abstract void accept (IVisitor visitor);}/*** specific implementation element class for visitors. * 1. Implement specific business logic. * 2. Set the visitor to access * @ author admin **/class ConcreteElement1 extends Element {@ Overridepublic void doSomenthing () {System. out. println ("I am the actual implementer of element 1... ") ;}@ Overridepublic void accept (IVisitor visitor) {visitor. visit (this) ;}}/*** specific implementation element class. * 1. Implement specific business logic. * 2. Set the visitor to access * @ author admin **/class ConcreteElement2 extends Element {@ Overridepublic void doSomenthing () {System. out. println ("I am the actual implementer of element 2... ") ;}@ Overridepublic void accept (IVisitor visitor) {visitor. visit (this) ;}}/*** abstract visitor, * declares the class that the visitor can access. Specific execution methods include subclass implementation * @ author admin **/interface IVisitor {// define the specific implementation of accessing the ConcreteElement1 class public void visit (ConcreteElement1 con1 ); // define the specific implementation of the access ConcreteElement2 class public void visit (ConcreteElement2 con2);}/*** specific implementation class of the visitor, * what will the visitor do after accessing the class, this class is available for implementation * @ author admin **/class ConcreteVisitor implements IVisitor {@ Overridepublic void visit (ConcreteElement1 con1) {con1.doSomenthing (); System. out. println ("---- visitor 1, run Task ") ;}@ Overridepublic void visit (ConcreteElement2 con2) {con2.doSomenthing (); System. out. println ("---- visitor 2, execute the task") ;}/ *** element, used to generate the object of the visitor type. * @ Author admin **/class ObjectStruture {// use a Random number to generate public static Element createElement () {random Random = new Random (); if (random. nextInt (100)> 50) {return new ConcreteElement1 ();} return new ConcreteElement2 ();}}

Example

A company has common employees and managers who have names, gender, and salary.
Private property: Employee: job, Manager: performance ).
A bunch of reports need to be printed here, requiring the division of employees and managers. How can we design it properly?

Public class VisitorT {public static void main (String [] args) {// print the report of the company's employees for (Emploee e: mockEmploy () {e. accept (new EmployeeVisitor () ;}// simulates all employees of the company. Public static List
 
  
MockEmploy () {List
  
   
EmployeeList = new ArrayList
   
    
(); // Create some common employees: Employer common1 = new Employer (); common1.setName ("lz"); common1.setJob ("APP listing .. "); common1.setSalary (12000); common1.setSex (1); Employer common2 = new Employer (); common2.setName (" ly "); common2.setJob (" APP is listed .. "); common2.setSalary (11000); common2.setSex (1); Employer common3 = new Employer (); common3.setName (" ht "); common3.setJob (" art done well .. "); common3.setSalary (10000); common3.setSex (2); // defines a Manager Ma Nager m = new Manager (); m. setName ("lzl"); m. setw.mence ("You must work overtime this evening... "); m. setSalary (1000000); m. setSex (1); // Add employeeList. add (common3); employeeList. add (common1); employeeList. add (common2); employeeList. add (m); return employeeList;}/*** abstract employee Report class, * defines common attribute methods. * Provides an observer class interface * @ author admin **/abstract class Emploee {private String name; private int sex; private double salary; public String getName () {return name;} public void setName (String name) {this. name = name;} public int getSex () {return sex;} public void setSex (int sex) {this. sex = sex;} public double getSalary () {return salary;} public void setSalary (double salary) {this. salary = salary;} public abstrac T void accept (IEmployeeVisitor visitor);}/*** the specific implementation class of the manager class. * @ Author admin **/class Manager extends Emploee {// The Manager is concerned with the company's private String queue mence; public String getqueue mence () {return queue mence ;} public void setinclumence (String inclumence) {this. required mence = required mence;} @ Overridepublic void accept (IEmployeeVisitor visitor) {visitor. visit (this) ;}}/*** implementation class of common employees. * @ Author admin */class Employer extends Emploee {// focus on private String job; public String getJob () {return job;} public void setJob (String job) {this. job = job;} @ Overridepublic void accept (IEmployeeVisitor visitor) {visitor. visit (this) ;}}/*** report observer interface class, * sets the observer to observe the specific implementation class. * The specific implementation method is implemented by the Implementation class * @ author admin **/interface IEmployeeVisitor {// set and observe the public void visit (Employer employer) of common employees ); // set the observer Manager public void visit (manager Manager);}/*** specific observer implementation class. * The observer is observed in the Implementation class, and then the report needs to be printed. * @ Author admin **/class EmployeeVisitor implements IEmployeeVisitor {@ Overridepublic void visit (Employer employer) {System. out. println (this. getEmployerInfo (employer);} @ Overridepublic void visit (Manager manager) {System. out. println (this. getManageInfo (manager);} // obtain the basic common information of an employee. private String getBaseInfo (Emploee e) {String info = "name:" + e. getName () + "\ t Gender:" + (e. getSex () = 1? "Male": "female") + "\ t salary:" + e. getSalary (); return info;} // obtain all Manager Information. private String getManageInfo (Manager m) {String info = m. getinclumence (); return info + "\ t" + getBaseInfo (m);} // obtain all information about a common employee. private String getEmployerInfo (Employer e) {String info = e. getJob (); return info + "\ t" + getBaseInfo (e );}}
   
  
 
Visitor mode Extension

--- | Statistical function

Interface IEmployeeVisitor {// set and observe the common employee public void visit (Employer employer); // set the observation Manager public void visit (manager Manager ); // public void totalSalary ();}/*** specific observer implementation class. * The observer is observed in the Implementation class, and a report needs to be printed. * @ Author admin **/class EmployeeVisitor implements IEmployeeVisitor {// total manager salary private double totalManager = 0; // general employee salary private double totalEmployer = 0; @ Overridepublic void visit (Employer employer) {this. getEmployer (employer) ;}@ Overridepublic void visit (Manager manager) {this. getManagerSalary (manager);} // calculates the total salary @ Overridepublic void totalSalary () {System. out. println ("the company's salary for one year is:" + this. totalEmployer + this. totalManager);} // Statistics Manager's salary private void getManagerSalary (Manager m) {this. totalManager = this. totalManager + m. getSalary ();} // calculate the employee's salary. private void getEmployer (Employer e) {this. totalEmployer = this. totalEmployer + e. getSalary ();}}

Advantages of visitor mode:
Compliant with the single Responsibility Principle
Excellent scalability
High flexibility
Disadvantages of visitor mode:
Detailed information about visitors
It is difficult to change specific elements.
The dependency inversion principle is violated.

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.