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

后端 未结 16 2031
春和景丽
春和景丽 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: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.

提交回复
热议问题