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

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

    You probably mean template method pattern. You are right, they serve very similar needs. I would say it is better to use template method in cases when you have a "template" algorithm having defined steps where subclasses override these steps to change some details. In case of strategy, you need to create an interface, and instead of inheritance you are using delegation. I would say it is a bit more powerful pattern and maybe better in accordance to DIP - dependency inversion principles. It is more powerful because you clearly define a new abstraction of strategy - a way of doing something, which does not apply to template method. So, if this abstraction makes sense - use it. However, using template method may give you simpler designs in simple cases, which is also important. Consider which words fit better: do you have a template algorithm? Or is the key thing here that you have an abstraction of strategy - new way of doing something

    Example of a template method:

    Application.main()
    {
    Init();
    Run();
    Done();
    }
    

    Here you inherit from application and substitute what exactly will be done on init, run and done.

    Example of a strategy:

    array.sort (IComparer comparer)
    

    Here, when writing a comparer, you do not inherit from an array. Array delegates the comparison algorithm to a comparer.

提交回复
热议问题