Easyhost Easyhost Easyhost Easyhost Easyhost

Visitor design pattern

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?

  1. Let’s say all the object in the heterogeneous collection of objects implement Element interface.
  2. Create a Visitor base class with a visit(ElementXxx) method for each Element derived type.
  3. 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 ); }.
  4. Create a Visitor derived class for each „operation” to be performed on Element objects. visit()implementations will rely on the Element’s public interface.
  5. 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.