This article describes the use of visitor mode to solve the company's hierarchical structure diagram problem. Share it for your reference, as follows:
1. Pattern definition
Visitor mode: represents an operation that acts on each element in an object structure. It allows the user to define new operations that act on these elements without changing the class of each element.
2. Model examples
1 Pattern Analysis
We borrow the company hierarchy to illustrate this model.
2 Visitor mode static class diagram
3 Code Examples
3.1 Abstract Staff
package com.demo.structure;import com.demo.visitor.IVisitor;/** * Abstract employee class* * @author * */public abstract class Staff { // Employee number protected String no; // Employee name protected String name; // Position protected String position; // Salary protected float salary; // Private property length string private int length; // Construct method public Staff(String no, String name, String position, float salary) { this.no = no; this.name = name; this.position = position; this.salary = salary; // Calculate the total byte length this.length += (no == null || "".equals(no.trim())) ? 0 : no.getBytes().length; this.length += (name == null || "".equals(name.trim())) ? 0 : position.getBytes().length; this.length += (position == null || "".equals(position.trim())) ? 0 : position.getBytes().length; this.length += String.valueOf(salary).getBytes().length; } // Get basic user information public void printUserBaseInfo() { System.out.println("-|" + this.no + " " + this.name + " " + this.position + " " + this.salary); } // Add employee information public abstract void add(Staff staff); // Delete employee public abstract Staff remove(String no); // Receive visitor object public abstract void accept(IVisitor visitor); public String getNo() { return no; } public void setNo(String no) { this.no = no; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public float getSalary() { return salary; } public void setSalary(float salary) { this.salary = salary; }}3.2 Manager
package com.demo.structure;import java.util.ArrayList;import com.demo.visitor.IVisitor;/** * Manager (someone with other employees under their command) * * @author * */public class Manager extends Staff { // Store information about employees private final ArrayList<Staff> arrayList = new ArrayList<Staff>(); // Construct method public Manager(String no, String name, String position, float salary) { super(no, name, position, salary); } /** * Add an employee*/ @Override public void add(Staff staff) { this.arrayList.add(staff); } /** * Delete employee information*/ @Override public Staff remove(String no) { Staff staff = null; if (no != null && !"".equals(no.trim())) { for (int i = 0; i < this.arrayList.size(); i++) { if (this.arrayList.get(i) == null) { continue; } if (no.equals(this.arrayList.get(i).getNo())) { staff = this.arrayList.remove(i); break; } } } return staff; } // Receive visitor object @Override public void accept(IVisitor visitor) { // Access your own visitor.visit(this); // traverse various element objects in the list list and receive visitor object for (int i = 0; i < this.arrayList.size(); i++) { if (this.arrayList.get(i) == null) { continue; } // Receive visitor object this.arrayList.get(i).accept(visitor); } }}3.3 Ordinary Employees
package com.demo.structure;import com.demo.visitor.IVisitor;/** * Ordinary employees (real people working) * * @author * */public class Employees extends Staff{ // Construct method public Employees(String no, String name, String position, float salary) { super(no, name, position, salary); } /** * Add employee information*/ @Override public void add(Staff staff) { return; } /** * Delete employee information*/ @Override public Staff remove(String no) { // Return null directly to null; } // Receive the visitor object public void accept(IVisitor visitor) { visitor.visit(this); }}3.4 Visitor interface-IVisitor
package com.demo.visitor;import com.demo.structure.Employees;import com.demo.structure.Manager;/** * Visitor interface* * @author * */public interface IVisitor { // Access manager public void visit(Manager manager); // Access ordinary employees public void visit(Employees employees);}3.5 Employee Basic Information Visitors PrintBaseInfoVistor
package com.demo.visitor;import com.demo.structure.Employees;import com.demo.structure.Manager;/** * Print basic information Visitor* * @author * */public class PrintBaseInfoVisitor implements IVisitor { /** * Access manager object*/ public void visit(Manager manager) { System.out.print("- Manager: "); manager.printUserBaseInfo(); } /** * Access ordinary employee object*/ public void visit(Employees employees) { System.out.print("- General employee:"); employees.printUserBaseInfo(); }}3.6 Create a visitor interface for stating employee salaries - ISalaryVistor
package com.demo.visitor;/** * Calculate salary visitor* * @author * */public interface ISalaryVisitor extends IVisitor { // Statistics manager salary public void printManagerTotalSalary(); // Statistics general employee salary public void printEmployeesTotalSalary(); // Statistics all employees salary public void printTotalSalary();}3.7 Statistics of employee salary and visitors to realize a SalaryVistor
package com.demo.visitor;import com.demo.structure.Employees;import com.demo.structure.Manager;/** * Specific implementation of calculating salary visitor* * @author * */public class SalaryVisitor implements ISalaryVisitor { // Total manager salary private float managerSalary; // Total salary of ordinary employees private float employeesSalary; public SalaryVisitor() { managerSalary = 0; employeesSalary = 0; } // Access manager public void visit(Manager manager) { managerSalary += manager.getSalary(); } // Visit ordinary employees public void visit(Employees employees) { employeesSalary += employees.getSalary(); } // Statistics the salary of general employees public void printEmployeesTotalSalary() { System.out.println("General employee salary sum: " + employeesSalary); } // Statistics the salary of managers public void printManagerTotalSalary() { System.out.println("Manager salary sum: " + managerSalary); } // Statistics of all employees' salaries public void printTotalSalary() { System.out.println("Employer Salary:" + (managerSalary + employeesSalary)); }}3.8 Client Testing a Client
package com.demo;import com.demo.structure.Employees;import com.demo.structure.Manager;import com.demo.structure.Staff;import com.demo.visitor.PrintBaseInfoVisitor;import com.demo.visitor.SalaryVisitor;/** * Main application* * @author * */public class Client { /** * @param args */ public static void main(String[] args) { // Company CEO Staff boss = new Manager("1", "Big Boss", "CEO", 100000); /** * The CEO has several department managers*/ // Finance Department Manager Staff financeManager = new Manager("11", "President Zhang", "Finance Manager", 60000); // Human Resources Department Manager Staff personnelManager = new Manager("12", "President Wang", "President Manager", 60000); // Technical Department Manager Staff technicalManager = new Manager("13", "President Chen", "Technical Department Manager", 60000); /** * There are also assistants and several supervisors in the technical department*/ // Technical Department Assistant Staff deptAssistant = new Manager("1301", "Assistant Wang", "Department Assistant", 20000); // Technical Department Director1 Staff deptManager1 = new Manager("1302", "Supervisor1", "Technical Director", 30000); /** * Technical Director DeptManager1 There are software engineers (the person who ends up working) */ Staff softwareEngineer1 = new Employees("1302001", "Zhang San", "Software Engineer", 5000); Staff softwareEngineer2 = new Employees("1302002", "Li Si", "Software Engineer", 5500); Staff softwareEngineer3 = new Employees("1302003", "Wang Wu", "Software Engineer", 4500); // Add employee information for technical supervisor 1 deptManager1.add(softwareEngineer1); deptManager1.add(softwareEngineer2); deptManager1.add(softwareEngineer3); // Technical Department Director 2 Staff deptManager2 = new Manager("1303", "Supervisor2", "Technical Director", 30000); // Add: Department Assistant, Technical Director 1 and Technical Director 2 technicalManager.add(deptAssistant); technicalManager.add(deptManager1); technicalManager.add(deptManager2); // Marketing Manager Staff marketingManager = new Manager("14", "Mr. Wu", "Market Manager", 60000); // Add to CEO: Finance Department Manager, Human Resources Department Manager, Technical Department Manager and Marketing Manager boss.add(financeManager); boss.add(personnelManager); boss.add(technicalManager); boss.add(marketingManager); // Print CEO information// boss.printUserBaseInfo(); // Print the CEO's employee information boss.accept(new PrintBaseInfoVisitor()); /** * Statistics employee salary*/ // Create a statistics employee salary visitor SalaryVisitor visitor = new SalaryVisitor(); // Let the big boss accept the visitor boss.accept(visitor); // Manager salary statistics visitor.printManagerTotalSalary(); // General employee salary statistics visitor.printEmployeesTotalSalary(); // All employee salary statistics visitor.printTotalSalary(); }}4 Running results
- Manager: -|1 Big Boss CEO 100000.0
- Manager: -|11 General Zhang Finance Department Manager 60000.0
- Manager: -|12 General Wang Human Resources Department Manager 60000.0
- Manager: -|13 General Chen Technical Department Manager 60000.0
- Manager: -|1301 Assistant Wang Department Assistant 20000.0
- Manager: -|1302 Supervisor 1 Technical Supervisor 30000.0
- General Employees: -|1302001 Zhang San Software Engineer 5000.0
- General Employees: -|1302002 Li Si Software Engineer 5500.0
- General Employees: -|1302003 Wang Wu Software Engineer 4500.0
- Manager: -|1303 Supervisor 2 Technical Supervisor 30000.0
- Manager: -|14 General Manager Wu Marketing Department 60000.0
Total manager salary: 420,000.0
Total salary of general employees: 15000.0
Total employee salary: 435,000.0
III. The design principles of this pattern
1 "Open-Close" principle
2 Single responsibility principle
4. Use occasions
1 If you include many different types of objects in an object structure, they have different interfaces, and you want to implement some operations that depend on specific classes on these different objects.
2 You need to perform many different and unrelated operations on objects in an object structure, and you want to avoid relating these operations to the classes of these objects. Visitor mode allows related operations to be centralized and defined separately in a class.
3 When this object structure is shared by many applications, use the visitor mode to allow each application to contain only the operations that need to be used.
4 The classes that define the object structure rarely change, but new operations are often required to define in this structure.
5. Visitor mode static class diagram
For more Java-related content, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.