The Visitor Pattern, Revisited
Sometimes, you need to perform an operation over a data structure that includes many different types of data. But, you don't want to build the operation into the objects themselves, either because you can't, or because you don't want to modify every class every time you have a new kind of operation. For example, you might want to have operations to:
- "Pretty print" a complex data structure
- Export the data structure to XML
- Compile or interpret a data structure (such as an abstract syntax tree)
But, if you're working with existing classes, and adding a new operation, you don't necessarily want to have to insert the code into every class. And if someone else wrote the code, you may not even have the option of doing that.