Chapter 26. The Visitor Pattern
The Visitor pattern turns the tables on our OO model and creates an external class to act on data in other classes. This is useful when you have a polymorphic operation that cannot reside in the class hierarchy for some reason. For example, the operation wasn't considered when the hierarchy was designed or because it would clutter the interface of the classes unnecessarily.
Motivation
While at first it might seem "unclean" to put operations that should be inside of a class in another class instead, there are good reasons for doing this. Suppose that each of a number of drawing object classes has similar code for drawing itself. The drawing methods might differ, but they probably all use underlying utility functions ...
Get Java™ Design Patterns: A Tutorial now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.