Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the template method and the strategy patterns?

People also ask

What is the difference between strategy and template design pattern?

But, the key difference is that Strategy Pattern is about modifying a behaviour of a context in runtime using strategies, while Template Method Pattern is about following a skeleton implementation of an algorithm and modifying its behaviour by overriding methods of the skeleton class in the subclasses.

What is the difference between template and pattern?

A template is a master pattern (in word processing a standard sequence of words, phrases or sentences) which is copied by the user, who can normally add something (e.g. someone's name) to it. A pattern (as used in social security numbers) is a sequence of data that follows a rule.

What is the difference between pattern and strategies?

The difference simply lies in that they solve different problems: The State pattern deals with what (state or type) an object is (in) -- it encapsulates state-dependent behavior, whereas. the Strategy pattern deals with how an object performs a certain task -- it encapsulates an algorithm.

What is Template Method pattern in design pattern?

Template method design pattern is to define an algorithm as a skeleton of operations and leave the details to be implemented by the child classes. The overall structure and sequence of the algorithm are preserved by the parent class. Template means Preset format like HTML templates which has a fixed preset format.


The template pattern is used when a particular operation has some invariant behavior(s) that can be defined in terms of other varying primitive behaviors. The abstract class defines the invariant behavior(s), while the implementing classes defined the dependent methods.

In a strategy, the behavior implementations are independent -- each implementing class defines the behavior and there is no code shared between them. Both are behavioral patterns and, as such, are consumed in much the same way by clients. Typically strategies have a single public method -- the execute() method, whereas templates may define a set of public methods as well as a set of supporting private primitives that subclasses must implement.

The two patterns could easily be used together. You might have a strategy pattern where several implementations belong to a family of strategies implemented using a template pattern.


The main difference between the two is when the concrete algorithm is chosen.

With the Template method pattern this happens at compile-time by subclassing the template. Each subclass provides a different concrete algorithm by implementing the template's abstract methods. When a client invokes methods of the template's external interface the template calls its abstract methods (its internal interface) as required to invoke the algorithm.

class ConcreteAlgorithm : AbstractTemplate
{
    void DoAlgorithm(int datum) {...}
}

class AbstractTemplate
{
    void run(int datum) { DoAlgorithm(datum); }

    virtual void DoAlgorithm() = 0; // abstract
}

In contrast, the Strategy pattern allows an algorithm to be chosen at runtime by containment. The concrete algorithms are implemented by separate classes or functions which are passed to the strategy as a parameter to its constructor or to a setter method. Which algorithm is chosen for this parameter can vary dynamically based on the program's state or inputs.

class ConcreteAlgorithm : IAlgorithm
{
    void DoAlgorithm(int datum) {...}
}

class Strategy
{
    Strategy(IAlgorithm algo) {...}

    void run(int datum) { this->algo.DoAlgorithm(datum); }
}

In summary:

  • Template method pattern: compile-time algorithm selection by subclassing
  • Strategy pattern: run-time algorithm selection by containment

I think the Class-Diagrams of both pattern are showing the differences.

Strategy
Encapsulates an algorithm inside a class
Link to image enter image description here

Template Method
Defer the exact steps of an algorithm to a subclass
Link to Image enter image description here


You probably mean template method pattern. You are right, they serve very similar needs. I would say it is better to use template method in cases when you have a "template" algorithm having defined steps where subclasses override these steps to change some details. In case of strategy, you need to create an interface, and instead of inheritance you are using delegation. I would say it is a bit more powerful pattern and maybe better in accordance to DIP - dependency inversion principles. It is more powerful because you clearly define a new abstraction of strategy - a way of doing something, which does not apply to template method. So, if this abstraction makes sense - use it. However, using template method may give you simpler designs in simple cases, which is also important. Consider which words fit better: do you have a template algorithm? Or is the key thing here that you have an abstraction of strategy - new way of doing something

Example of a template method:

Application.main()
{
Init();
Run();
Done();
}

Here you inherit from application and substitute what exactly will be done on init, run and done.

Example of a strategy:

array.sort (IComparer<T> comparer)

Here, when writing a comparer, you do not inherit from an array. Array delegates the comparison algorithm to a comparer.


Difference between Strategy and Template Method Pattern Strategy vs Template method


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:

  1. In Strategy, the coupling between the client and strategy is more loose whereas in Template Method, the two modules are more tightly coupled.
  2. 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.
  3. 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.
  4. 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.


Inheritance versus aggregation (is-a versus has-a). It's two ways to achieve the same goal.

This question shows some of trade-offs between choices: Inheritance vs. Aggregation