Here’s a post about an interesting behavioral design pattern called Visitor.
This design pattern should be applied for a stable collection of objects which implement the same interface.
What is it good for? We can use it in different scenarios. Let’s see only a few of them :
- You want to implement different operations on a collection of different objects, but you don’t want to change their classes.
- You want to collect data from a collection of unrelated classes and present that data in a comprehensive way.
- You want an easy way to recover the type of a certain object.
- You want the right method to be applied depending on the type of object received as a parameter.
How to do it?
- Let’s say all the object in the heterogeneous collection of objects implement Element interface.
- Create a Visitor base class with a
visit(ElementXxx)
method for each Element derived type. - Add an
accept(Visitor)
method to the Element hierarchy. The implementation in each Element derived class is always the same –accept( Visitor v ) { v.visit( this ); }
. - Create a Visitor derived class for each “operation” to be performed on Element objects.
visit()
implementations will rely on the Element’s public interface. - The client creates Visitor objects and passes each to Element objects by calling
accept()
.
For more information about this design pattern, read this post. It also contains C++ and java implementations examples.