何时使用模板方法战略? [英] When to use template method Vs. Strategy?
问题描述
模板方法模式和策略模式大致相同。我了解他们之间的基本差异(模板方法是基于继承,策略是基于组合),但是是否有任何体面的指导方针来选择一个?看起来他们基本上是一样的。
The template method pattern and the strategy pattern do roughly the same thing. I understand the basic differences between them (template method is inheritance based, strategy is composition based), but are there any decent guidelines on when to choose one over the other? It seems like they do basically the same thing.
推荐答案
当算法需要对象的内部知识时,我使用Template方法它运行在。
I use Template method when the algorithm needs knowledge of the internals of the objects it runs on.
在所有其他情况下(即当算法只需要使用对象的界面)时,我尝试使用策略。
In all other cases (i.e. when the algorithm only needs to use the object's interface), I try to use Strategy.
此外,策略仅在实际执行算法时才有用:如果类之间的唯一区别是(例如)返回的简单值,请使用Template方法。
Further, Strategy is only useful when there are actual algorithms to implement: If the only difference between classes is (for example) what simple value to return, use Template method.
这篇关于何时使用模板方法战略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!