From the course: Complete Guide to Java Design Patterns: Creational, Behavioral, and Structural

Unlock this course with a free trial

Join today to access over 25,300 courses taught by industry experts.

Understand the Visitor pattern

Understand the Visitor pattern

Imagine you have a tree structure of objects, and you want to perform an operation on all the elements of it. The visitor pattern allows you to do this without making changes to the elements themselves. Instead, you have a separate visitor objects, which is passed to each object to perform the operation. As a real-world analogy, imagine someone drives a car to a mechanic. The mechanic temporarily takes over the car to fix some things, and then the car is driven away again. The mechanics might do different kinds of fixes depending on the problem, and there also might be different kinds of vehicles, such as trucks and buses and so on. The different fixes might be similar for each different type of vehicle, but also slightly different. Let's see what the visitor pattern looks like in a Java program. So let's say you have an interface with some concrete implementations of it. And let's say you want to apply some operation to each of the concrete implementations. The operation will be…

Contents