Simberon Design Minute
 

Visitor Design Pattern

The visitor design pattern allows you to iterate over a collection of objects performing an operation that's specific to the kind of each object. It does this by passing a visitor object to each element and having each element send a message back to the visitor. Each different class of object would send a different message to the visitor.

A common fallacy of the visitor pattern is that it's only used for trees of objects. In fact, a visitor can be used on any kind of collection so long as you have a way of iterating over the collection. If you keep track of the objects you've already visited, it can even be used over a connected network of objects. The visitor pattern can be tough to extend if you add new classes of objects to your collection. When you do so, you need to add a new method to all visitors or at least implement a method in the superclass. You should keep in mind that the visitor pattern is a rather complex solution and may not always be appropriate. Sometimes a simple iterator will work just as well.

Download