Design Pattern – Strategy Vs Template Method

Connect with

There are some similarity and some differences between both i.e. Template Method and Strategy design pattern. Here , I tried to collect for better understanding .

Strategy Pattern

“Define a family of algorithm and make them interchangeable. “

As we know, each algorithm is encapsulated , the client can use different algorithm easily.

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 do 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.

Key Points of Strategy and Template Method

  • 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”

please write you thought or comment to improve this article.


Connect with