From the course: Java Design Patterns: Behavioral Part 2

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Understanding the Visitor pattern

Understanding the Visitor pattern - Java Tutorial

From the course: Java Design Patterns: Behavioral Part 2

Start my 1-month free trial

Understanding the Visitor pattern

- [Bethan] Say you have a tree 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, a separate visitor object is passed to each object to perform the operation. As a real world analogy, imagine someone drives a car to a mechanic's. The mechanics temporarily take 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. 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…

Contents