30

The Visitor Pattern

The Visitor pattern turns the tables on the object-oriented model and creates an external class to act on data in other classes. This is useful if there are a fair number of instances of a small number of classes and you want to perform some operation that involves all or most of them.

When to Use the Visitor Pattern

While at first it may seem “unclean” to put operations that should be inside one class into another class instead, there are good reasons for doing it. Suppose each of multiple drawing object classes has similar code for drawing itself. The drawing methods may be different, but they probably all use underlying utility functions that we might have to duplicate in each class. Furthermore, a set of closely related ...

Get Python Programming with Design Patterns 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.