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

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

    Template Method:

    1. It's based on inheritance
    2. Defines skeleton of algorithm which can't be changed by sub classes. Only certain operations can be overridden in sub classes
    3. Parent class completely controls the algorithm and differs only certain steps to concrete classes
    4. Binding is done at compile time

    Template_method structure:

    Strategy:

    1. It's based on delegation/composition
    2. It changes guts of the object by modifying method behaviour
    3. It's used to switch between family of algorithms
    4. It changes the behaviour of the object at run time by completely replacing one algorithm with other algorithm at run time
    5. Binding is done at run time

    Strategy structure:

    Have a look at Template method and Strategy articles for better understanding.

    Related posts:

    Template design pattern in JDK, could not find a method defining set of methods to be executed in order

    Real World Example of the Strategy Pattern

提交回复
热议问题