Behavioral Patterns - Visitor Pattern Exercise
The Visitor Pattern represents an operation to be performed on elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. In this exercise, we will create a bookstore inventory structure that collects books, movies, and music. We will add shared behaviors across this hierarchical structure by using the Visitor Pattern.
Reading Materials
- https://en.wikipedia.org/wiki/Visitor_pattern (15 minutes reading)
Practice Materials
- Use the Visitor Pattern to create a bookstore inventory that meets the following requirements:
- the bookstore inventory collects books, movies, and music.
- all these three media types have their own members and one common member - title
- add one behavior to the media so that the operation can print out all the titles.
- add second behavior to the media so that the operation can print out details of all media and the total count of media while the media is traversed.
Components:
- Visitor Interface (The operation that is shared across visited elements) -
MediaVisitor
- Element Interface (The hierarchical structure that accepts the operation from a visitor) -
Media
- Concrete Elements (The elements in the hierarchical structure that will be visited) -
Book
,Movie
,Music
- Concrete Visitors (Each visitor will define one type of operation) -
TitlePrintingVisitor
,DetailPrintingVisitor
- Iterator for traversal (The root structure that holds the references to all the sub-elements) -
Inventory
Tips
- Visitors can have their own internal state to keep track of the elements they visit.
Solution
Questions to discuss
- What are the common use cases to apply the Template Method Pattern?
- What are the two major disadvantages of the Visitor Pattern?
- Break Encapsulation
- Difficult to add more subclasses to the hierarchical structure
Comments
Post a Comment