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.
Creating a visitor - Java Tutorial
From the course: Java Design Patterns: Behavioral Part 2
Creating a visitor
- [Instructor] In this example, I have an application that keeps a list of groceries. The visitor pattern can be quite complex, so I've kept this example as simple as possible. So first of all, there is an interface called Groceries, which has a single method in it called getPrice. There are three concrete implementations of groceries. The first one is called Bread. This is a field of type double called price, and this is set to 1. Then I've got a setter method and a getter method, so I've got setPrice and getPrice. The second implementation is called Milk. So if I open up the Milk class, I can see it's exactly the same as the Bread class, except that the price in this one is set to 2. The third implementation is called GroceryList, which is slightly different. And this is a list of all the grocery items. So it has a field called groceries, which is an ArrayList containing Groceries items. In the constructor, I'm…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.