Design Patterns in Java - Visitor Pattern
Today, we are going to learn one of the most useful patterns, the Visitor Pattern.
What is the Visitor pattern? Well, let's look at an example.
Let's say you're a software engineer working at a university. The university rarely has established honors standards. These standards fall into three categories: research-centered, academic-centered, and mixed methods. Every year, the school's board of directors randomly selects a strategy to see which students and professors qualify for the award.
Assume you have implemented the following class:
Student 类
public class Student extends Person { int researchScore; int academicScore; int hybridScore; public int getResearchScore() { return researchScore; } public void setResearchScore(int researchScore) { this.researchScore = researchScore; } public int getAcademicScore() { return academicScore; } public void setAcademicScore(int academicScore) { this.academicScore = academicScore; } public int getHybridScore() { return hybridScore; } public void setHybridScore(int hybridScore) { this.hybridScore = hybridScore; } }
Professor 类
public class Professor extends Person { int researchScore; int academicScore; int hybridScore; public int getResearchScore() { return researchScore; } public void setResearchScore(int researchScore) { this.researchScore = researchScore; } public int getAcademicScore() { return academicScore; } public void setAcademicScore(int academicScore) { this.academicScore = academicScore; } public int getHybridScore() { return hybridScore; } public void setHybridScore(int hybridScore) { this.hybridScore = hybridScore; } }
You have implemented Student and Professor POJO classes. We also have a parent class Person that Professor and Student inherit from . Also, to evaluate the scores and who is eligible for rewards, we will implement a Manager class that has a function that will evaluate different people with different strategies.assessPeople(Person person, int strategy)
Manager 类
public class Manager { /** * 0 表示 research 方法 * 1 表示 academic 方法 * 2 表示 hybrid 方法 */ int strategy; public void assessPeople(Person person, int strategy) { // 很大程度上取决于 Person 的类型和 strategy 类型。 } }
Now, if we take the traditional approach, we will write a lot of if statements in the Manager class: we have to write logic for each award selection strategy for each type of person (student, professor). In our case, we can handle this, but what if we want to evaluate 5,6,..10 strategies and 5 types of people? The code will quickly become unmanageable.
Fortunately, we can have the following Visitor Pattern to the rescue. We will design a simple Visitor interface. It just declares two abstract functions named visit
.
AssessVisitor 接口
public interface AssessVisitor { abstract public void Visit(Student student); abstract public void Visit(Professor professor); }
Note here that we have not applied any specific strategy. Instead, we have created three concrete classes for each of these strategies, as shown below:
ResearchApproach 类
public class ResearchApproach implements AssessVisitor { @Override public void Visit(Student student) { if(student.getResearchScore() >= 70) { System.out.println("The student is on deans list based on ResearchApproach"); } } @Override public void Visit(Professor professor) { if(professor.getResearchScore() >= 70) { System.out.println("The professor is on deans list based on ResearchApproach"); } } }
AcademicApproach 类
public class AcademicApproach implements AssessVisitor { @Override public void Visit(Student student) { if(student.getResearchScore() >= 70) { System.out.println("The student is on deans list based on AcademicApproach"); } } @Override public void Visit(Professor professor) { if(professor.getResearchScore() >= 70) { System.out.println("The professor is on deans list based on AcademicApproach"); } } }
HybridApproach 类
public class HybridApproach implements AssessVisitor { @Override public void Visit(Student student) { if(student.getResearchScore() >= 70) { System.out.println("The student is on deans list based on HybridApproach"); } } @Override public void Visit(Professor professor) { if(professor.getResearchScore() >= 70) { System.out.println("The professor is on deans list based on HybridApproach"); } } }
In both classes, we implemented the specific logic to evaluate whether a candidate is eligible for a reward.
Additionally, we will add an accept() function to the Person class and its subclasses.
Person 类
public class Person { public void getAssessed(AssessVisitor visitor) {} }
具有 getAssessed 方法的 Student类
public class Student extends Person { int researchScore; int academicScore; int hybridScore; public int getResearchScore() { return researchScore; } public void setResearchScore(int researchScore) { this.researchScore = researchScore; } public int getAcademicScore() { return academicScore; } public void setAcademicScore(int academicScore) { this.academicScore = academicScore; } public int getHybridScore() { return hybridScore; } public void setHybridScore(int hybridScore) { this.hybridScore = hybridScore; } @Override public void getAssessed(AssessVisitor visitor) { visitor.Visit(this); } }
具有 getAssessed 方法的 Professor 类
public class Professor extends Person { int researchScore; int academicScore; int hybridScore; public int getResearchScore() { return researchScore; } public void setResearchScore(int researchScore) { this.researchScore = researchScore; } public int getAcademicScore() { return academicScore; } public void setAcademicScore(int academicScore) { this.academicScore = academicScore; } public int getHybridScore() { return hybridScore; } public void setHybridScore(int hybridScore) { this.hybridScore = hybridScore; } @Override public void getAssessed(AssessVisitor visitor) { visitor.Visit(this); } }
Now, everything is ready, and all that's left to do is to modify our Manager class to a simple format:
Manager 类
public class Manager { public void assessPeople(Person person, AssessVisitor visitor) { person.getAssessed(visitor); } }
Now that everything is done, feel free to write a main method to test that it works!
Now, we will summarize the Visitor pattern beyond the example. Generally, the Visitor pattern appears if the behavior (functional logic) changes, or more abstractly, the Visitor pattern separates the content of the algorithmic pattern from the object it works on. In our example, the strategy changes, the type of person changes, and we use the Visitor pattern to decouple the evaluation and the logic of the person class.
Typically, a visitor pattern will have a visitor interface that has methods defined for different targets (classes). Then, whenever we need to add a new algorithm pattern or change one, we just need to implement a new class that implements the visitor interface. Then, in the object's class, we need to add a method that accepts a visitor object (anything that implements the visitor interface) and call that visitor.visit(this)
. After that, Java's polymorphism takes care of the rest. See the UML diagram below

As shown in the figure above, the logic of the access method is decoupled from the object.
Now that we understand the ins and outs of the Visitor pattern, have fun writing an example!
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Learning the Sorting Algorithm - Insertion Sort (Concepts)
Publish Date:2025/03/19 Views:95 Category:ALGORITHM
-
What is "insertion sort"? The concept is as follows: each time a record to be sorted is inserted into the previously sorted sequence according to its key size, until all records are inserted. Concepts are always somewhat abstract, and can a
Learning path of sorting algorithm - direct insertion sort
Publish Date:2025/03/19 Views:175 Category:ALGORITHM
-
This article follows up on Insertion Sort (Concepts) and presents the implementation steps and code for direct insertion sort. Since the Concepts section already has a large number of illustrations, it would be a bit long-winded to provide
Learning the sorting algorithm - Binary Insertion Sort
Publish Date:2025/03/19 Views:142 Category:ALGORITHM
-
This article follows the insertion sort (concept article) and presents the implementation steps and implementation code of the binary insertion sort Binary Insertion Sort Algorithm Steps Treat the first element of the first sequence to be s
The road to learning sorting algorithms - table insertion sort
Publish Date:2025/03/19 Views:193 Category:ALGORITHM
-
Table insertion sort was briefly mentioned in Insertion sort (concept) . I briefly summarized it and wrote this article. You can refer to it if you need it. Table insertion sort, as the name implies, uses an index table to sort the original
The road to learning sorting algorithms - Hill sort
Publish Date:2025/03/19 Views:50 Category:ALGORITHM
-
Hill sort is named after the designer of the algorithm, Hill. It is an improvement of Hill on the basis of insertion sort and can be said to be a special insertion sort. Here are the properties of insertion sort: First of all, the insertion
Things about the singleton design pattern
Publish Date:2025/03/19 Views:51 Category:ALGORITHM
-
The singleton design pattern is one of the most commonly used design patterns. The singleton design pattern, just by its name, you can roughly know its meaning. Single means one; instance means instance object. So a singleton has only one i
The road to learning sorting algorithms - merge sort
Publish Date:2025/03/19 Views:157 Category:ALGORITHM
-
Let's first look at the definition of merge sort Merge sort is an effective sorting algorithm based on the merge operation. This algorithm is a very typical application of the Divide and Conquer method. Merge the ordered subsequences to obt
The road to learning sorting algorithms - merge sort (non-recursive implementatio
Publish Date:2025/03/19 Views:188 Category:ALGORITHM
-
In the article "Merge Sort", we introduced the principles and operation steps of merge sort, and finally implemented the sorting algorithm using PHP code. In the program, we used the principle of recursion to implement the algorithm. In fac
The road to learning sorting algorithms - quick sort
Publish Date:2025/03/19 Views:121 Category:ALGORITHM
-
Quick sort is a sorting algorithm developed by Tony Hall. On average, sorting n items requires O(n log n) comparisons. In the worst case, O(n2) comparisons are required, but this is uncommon. In fact, quick sort is often significantly faste