What is the difference between the template method and the strategy patterns?
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
模板方法通过继承来处理,继承在写代码的时候,就已经决定了调用的算法的实现。
策略模式,是在运行的时候,才决定调用哪一个算法。通过传递进来的参数决定,这个参数编译的时候,并没有确定下来。