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

后端 未结 16 2026
春和景丽
春和景丽 2020-12-07 07:11

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 -

相关标签:
16条回答
  • 2020-12-07 07:17

    I would suggest you to read this article. It explains the differences on a real case example.

    Quote from the article

    "As one can see implementing classes also depend upon the template method class. This dependency causes to change the template method if one wants to change some of the steps of the algorithm. On the other side strategy completely encapsulates the algorithm. it gives the implementing classes to completely define an algorithm. Therefore if any change arrives one does need to change the code for previously written classes. This was the primary reason I choose strategy for designing up the classes.

    One feature of template method is that template method controls the algorithm. Which can be a good thing in other situation but in my problem this was restricting me to design the classes. On the other side strategy does not control the steps of an algorithm which enables me to add completely different conversion methods. Hence in my case strategy helps me for implementation.

    One drawback of strategy is that there is too much code redundancy and less code sharing. As it is obvious in the presented example of this article I have to repeat the same code in four classes again and again. Therefore it is hard to maintain because if the implementation of our system such as step 4 which is common to all is changed then I will have to update this in all 5 classes. On the other side, in template method, I can only change the superclass and the changes are reflected into the sub classes. Therefore template method gives a very low amount of redundancy and high amount of code sharing among the classes.

    Strategy also allows changing the algorithm at run-time. In template method one will have to re-initialize the object. This feature of strategy provide large amount of flexibility. From design point of view one has to prefer composition over inheritance. Therefore using strategy pattern also became the primary choice for development."

    0 讨论(0)
  • 2020-12-07 07:18

    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

    0 讨论(0)
  • 2020-12-07 07:21

    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

    myShippingCalculator.CalculateTaxes(myCaliforniaSalesTaxImpl);
    

    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.

    0 讨论(0)
  • 2020-12-07 07:21

    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.

    0 讨论(0)
  • 2020-12-07 07:22

    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.

    0 讨论(0)
  • 2020-12-07 07:25

    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

    0 讨论(0)
提交回复
热议问题