What is the difference between the template method

2019-01-29 15:08发布

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?

16条回答
萌系小妹纸
2楼-- · 2019-01-29 15:31

Both are very similar, and both are consumed by the client code in similar ways. Unlike what the most popular answer above says, both allow algorithm selection at run-time.

The difference between the two is that while the strategy pattern allows different implementations to use completely different ways of the achieving the desired outcome, the template method pattern specifies an overarching algorithm (the "template" method) which is be used to achieve the result -- the only choice left to the specific implementations (sub-classes) are certain details of the said template method. This is done by having the the template method make call(s) to one or more abstract methods which are overridden (i.e. implemented) by the sub-classes, unlike the template method which itself is not abstract and not overridden by the sub-classes.

The client code makes a call to the template method using a reference/pointer of the abstract class type pointing to an instance of one of the concrete sub classes which can be determined at run time just like while using the Strategy Pattern.

查看更多
相关推荐>>
3楼-- · 2019-01-29 15:32

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
查看更多
Juvenile、少年°
4楼-- · 2019-01-29 15:32

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.

查看更多
\"骚年 ilove
5楼-- · 2019-01-29 15:34

Strategy Design Pattern

  • Supports composition.
  • Provides you the flexibility to change the behavior of object at runtime.
  • Less coupling between the client code and the solution/algorithm code.

Template Method Design Pattern

  • Favours inheritance over composition
  • Define algorithm in your base class. Individual pieces of algorithm can be customized in child classes.
查看更多
放我归山
6楼-- · 2019-01-29 15:37

Strategy is exposed as an Interface and template method as the Abstract Class. This is typically used a lot in frameworks. e.g. Spring framework's MessageSource class is a strategy interface for resolving messages. Client uses particular implementation (strategy) of this interface.

And the abstract implementation of the same interface AbstractMessageSource, which has common implementation of resolving messages and exposes resolveCode() abstract method so that sub-classes can implement them in their ways. AbstractMessageSource is an example of template method.

http://docs.spring.io/spring/docs/4.1.7.RELEASE/javadoc-api/org/springframework/context/support/AbstractMessageSource.html

查看更多
手持菜刀,她持情操
7楼-- · 2019-01-29 15:42

In the template method of this design pattern, one or more algorithm steps can be overridden by subclasses to allow differing behaviors while ensuring that the overarching algorithm is still followed(Wiki).

The pattern name Template method means what it is. Say we have a method CalculateSomething() and we want to template this method. This method will be declared in the base class a non virtual method. Say the method looks like this.

CalculateSomething(){
    int i = 0;
    i = Step1(i);
    i++;
    if (i> 10) i = 5;
    i = Step2(i);
    return i;

} Step1 and Step2 method implementation can be given by derived classes.

In Strategy Pattern there is no implementation provided by the base (This is the reason why the base is really an interface in the class diagram)

The classic example is sorting. Based on the number of objects needs to be sorted the appropriate algorithm class(merge, bubble, quick etc.) is created and the entire algorithm is encapsulated in each class.

Now can we implement the sorting as a template method? Certainly you can, but you wont find much/any commonality to be abstracted out and placed in the base implementation. So it defeats the purpose of template method pattern.

查看更多
登录 后发表回答