Understanding Visitor Pattern

In Object Oriented Design, the visitor patter is one of the obscure pattern yet powerful enough to solve many complex OO scenarios. Visitor Pattern is also not really easy to understand at the first glance but you need to dig it around with practical examples. (I guess it’s not just for Visitor pattern but also for all the other patterns) I would like to give a clean and simple introduction to visitor pattern with this post. So let’s start with a simple example ofthe usage of Visitor pattern. Visitor Pattern is often useful when there are fair numbers of related classes. One of the common examples of such a scenario is ‘drawing different shapes’. In this case we have a set of related classes; Circle, Trangle, Rectangle etc. Now, if we are going to implement a draw() function for all these classes i.e. circle::draw(), trangle::draw().. etc we may be drawing different shapes but we are replicating a fair amount of code in all the classes. (Because the underlying methods, that we use to d...