Learn different aspects of Strategy Vs Template design patterns. Let me explain the similarity and differences between them.
There are some similarities and some differences between both i.e. Template Method and Strategy design patterns.
1. Strategy Pattern
“Define a family of algorithms and make them interchangeable. “
As we know, each algorithm is encapsulated, the client can use different algorithms easily.
2. Template Method Pattern
“Define the skeleton of an algorithm in an operation deferring some step to subclass.”
Template Method job is to define the outline of an algorithm, but my subclass does some of the work. It means, I ( Template) have more control over my algorithm and I don’t duplicate code.
All the duplicate code put into super class so that all subclass share those code.
3. Key Points of Strategy vs Template Method design patterns
Following are the different aspect and different view of Strategy and template method design patterns.
- Strategy and Template Method both encapsulate algorithm, Template by inheritance and strategy by composition.
- Template Method is much more efficient than Strategy, while Strategy is more flexible because use object composition.
- In template method all duplicate code are in super class so that all the subclass share those duplicate code. while in Strategy, few of the duplicate code can be in all the subclass.
- Strategy says , I don’t depend on anyone , I can do the entire algorithm my self. While Template says, I do not keep any duplicate code so I use important technique code reuse and much efficient.
- In Strategy , client can change their algorithm at runtime simply by using different strategy object.
- In Template , abstract methods are implemented by sub-classes. while not abstract method in Strategy, it’s self contained code.
- To prevent the subclass from changing the algorithm in the Template method , declare Template Method as
final
- Template Method and Hollywood Principle , do’t call Us we will call you .
- When we design with Template Method pattern, we are (template method) telling subclass, “don’t call us we will call you”
4. Reference
I hope you enjoyed this post of Strategy vs Template Method design pattern, and you can visit design patterns tutorial for more details.
Suggestions are welcome to improve this post. Happy Learning 🙂