I was reading about the Strategy Design Pattern. And, I observed that whatever we achieve in Strategy Design pattern the same thing we can achieve using Runtime Polymorphism in Java. So, I would like to know the actual difference between the two and how to decide which to choose when?
Well there is another design pattern that is basically the Strategy pattern using inheritance, the Template Method pattern.
They both work well, but the Strategy Pattern can be more flexible. If you wish to change the behaviour with the Template Method pattern then you need to create a new object. This isn't always convenient because there may be a set-up cost to that, it may interrupt work that was being done, and it often isn't convenient to make sure all references to the old instance are replaced with the new instance.
With the Strategy pattern you just need to create a new strategy and replace the old strategy with it, which can be done in just one place. This follows the OO design principle of Favour Composition over Inheritance.
As with all design patterns there is not one correct solution. A design pattern covers a whole class of related solutions, and the pros and cons of each solution is very much related to the context. If you change the context then the solution that best fits will be different.
I have gone to look for myself. If I should return before I get back, keep me here with this tiny ad:
a bit of art, as a gift, that will fit in a stocking