Can someone please explain to me what is the difference between the template method pattern and the strategy pattern is?
As far as I can tell they are 99% the same - the only difference being that the template method pattern has an abstract class as the base class whereas the strategy class uses an interface that is implemented by each concrete strategy class.
However, as far as the client is concerned they are consumed in exactly the same way - is this correct?
Template Method:
Template_method structure:
Strategy:
Strategy structure:
Have a look at Template method and Strategy articles for better understanding.
Related posts:
Template design pattern in JDK, could not find a method defining set of methods to be executed in order
Real World Example of the Strategy Pattern
In strategy pattern subclasses are running the show and they control the algorithm. Here code is duplicated across the subclasses. The knowledge of the algorithm and how to implement it is distributed over many classes.
In template pattern, base class has algorithm. It maximizes the reuse among the subclasses. Since algorithm lies in one place, base class protects it.
I think the Class-Diagrams of both pattern are showing the differences.
Strategy
Encapsulates an algorithm inside a class
Link to image
Template Method
Defer the exact steps of an algorithm to a subclass
Link to Image
No, they are not necessarily consumed in the same way. The "template method" pattern is a way of providing "guidance" to future implementers. You are telling them, "All Person objects must have a Social Security Number" (that's a trivial example but it gets the idea across correctly).
The strategy pattern allows multiple possible implementations to be switched in and out. It is not (usually) implemented through inheritance, but instead by letting the caller pass in the desired implementation. An example might be allowing a ShippingCalculator to be provided with one of several different ways of calculating taxes (a NoSalesTax implementation, and a PercentageBasedSalesTax implementation perhaps).
So, sometimes, the client will actually tell the object which strategy to use. As in
But the client would never do that for an object that was based on Template Method. In fact, the client might not even know an object is based on Template Method. Those abstract methods in the Template Method pattern might even be protected, in which case the client wouldn't even know they exist.