Similarities
Strategy and Template method patterns have a lot of similarities between them. Both Strategy and Template method patterns can be used for satisfying the Open-Closed Principle and making the software module easy to extend without changing its code. Both patterns represent separation of generic functionality from the detailed implementation of that functionality. However, they differ a little in terms of granularity they offer.
Differences
Here are some of the differences I have observed while studying these two patterns:
- In Strategy, the coupling between the client and strategy is more
loose whereas in Template Method, the two modules are more tightly
coupled.
- In Strategy, mostly an interface is used though abstract class can
also be used depending on the situation, and concrete class is not
used whereas in Template method mostly abstract class or concrete
class is used, interface is not used.
- In Strategy pattern, generally entire behaviour of the class is
represented in terms of an interface, on the other hand, Template method is used
for reducing code duplication and the boilerplate code is defined in
base framework or abstract class. In Template Method, there can even be a concrete class
with default implementation.
- In simple words, you can change the entire strategy (algorithm) in
Strategy pattern, however, in Template method, only some things
change (parts of algorithm) and rest of the things remain unchanged. In Template Method, the invariant steps are implemented in an abstract base class, while the
variant steps are either given a default implementation, or no
implementation at all. In Template method, the component designer
mandates the required steps of an algorithm, and the ordering of the
steps, but allows the component client to extend or replace some
number of these steps.
Image is taken from the bitesized blog.