Design patterns: Strategy v/s Visitor
Posted by Manoj Garg on February 4, 2010
Design patterns are recommended solution for some well-defined problems with a predefined context. As Wikipedia says:
“A ‘Design Pattern’ is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.”
Context is important while deciding which pattern to use in a given situation. There may be more than one qualifying pattern for a problem but all of them may or may not be suitable in that particular situation.
Some time back, I had implemented Visitor pattern for a problem. When a colleague of mine was reviewing it, we got into a discussion that this was best fit for a Strategy rather than Visitor pattern. That got me searching around for the right context and difference between these two so similar but yet so different pattern.
In visitor pattern the object structure accepts a visitor and performs visit on it. In strategy the only difference I could notice was that the composite or object structure composes a strategy object and calls Algorithm. Aren’t these two patterns essentially the same? Or rather can I put it like strategy is a cut down version of visitor or a visitor on a single type of element?
In the StrategyPattern, the context points to a strategy and delegates to it. There is no context in the VisitorPattern and the visitor is often created each time it is used. The VisitorPattern is based on DoubleDispatching, and there is none in the StrategyPattern. As far as I can see, these patterns have little to do with each other. —RalphJohnson
The intent of the visitor pattern is to add operations to a class which has rich data structure. If we are not able to identify all the operations in for the class but we expect in future we may need to add method for the class, but it is not advisable to alter the class, so to be on safer side we can put a visitor and share the data to the visitor class
The intent of strategy pattern is to define a family of algorithm, encapsulate each one, and make them interchangeable. Let the algorithm vary independently from the clients that use it. This pattern is used to add different algorithm nothing to do with the data in the class.
Here is an article by LEEDRICK discussing difference and similarities in these two patterns.
Please feel free to reply with your suggestions.