GoF Design Patterns – Visitor Design Pattern


The Visitor Design Pattern is a behavioral pattern that separates an algorithm from the elements on which it operates. It allows grouping similar operations together and executes operations on elements that the algorithm should process. The pattern is useful in situations where similar operations should be performed on a collection of different elements.

For example, let’s say we need to create an application that can provide financial indicators on financial instruments. Financial indicators will be things like Current Total Value, Yield, and Capital Gain. Financial instruments will be things like stocks and bonds. Each financial indicator is calculated differently for financial instruments, but operations are similar. The Visitor Design Pattern can be used to decompose such a problem efficiently.

The main idea behind the above example is for each financial calculator to be able to visit each financial instrument in the portfolio. When a financial calculator visits a financial instrument, it changes its internal state. For example, when a total value calculator visits a stock or bond, it calculates the stock or bond current total value. At the same time, the total value calculator changes its internal state to update the remembered total value of all visited financial instruments.

More on this pattern…

To read more on this and the other patterns, get “GoF Design Patterns Distilled” book from Amazon or Leanpub: