模板方法(分离)和策略模式之间的区别?
我的老师是一位非常好的老师,我倾向于理解他的观点,但这个问题超出了我的理解范围。 他用两种变体解释了模板方法;
- 统一:标准变体,由抽象类和一些定义固定算法的变体部分的抽象方法组成。
- 分离:他自己的变体(我认为?),其中一个类包含 templateMethod() 并使用对接口的委托来改变算法的各个部分,在我看来,这与策略模式完全相同。
谁能明白他的观点是什么,以及“分离”变体与策略模式有何不同?
我附上了一张包含他的书中的两种图案的图像(尚未出版)。
My teacher is a really good one and I tend to understand his points, but this one just goes over my head.
He explains Template Method in two variants;
- Unification: the standard variant, that is composed of an abstract class with some abstract methods defining the variant parts of the otherwise fixed algorithm.
- Separation: his own variant (I think?) where a class contains the templateMethod() and uses delegation to an interface to vary the parts of the algorithm, which looks to me exactly like the Strategy pattern.
Can anyone see what his point is, and how the 'separation' variant is different from the Strategy pattern?
I have attached an image containing the two patterns from his book (which isn't published yet).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我从未听说过模板方法模式的“分离变体”,并且我同意它看起来与策略极其相似。即使对接口所有权或如何从客户端角度调用它们有一些推理,我也几乎发现考虑它们不同的模式有任何好处。
I have never heard of a "Separation variant" of the Template method pattern, and I agree that it looks extremely similar to the Strategy. Even if there is some reasoning about interface ownership or how you invoke them from a client perspective I hardly find there's any benefit to consider them different patterns.
在常见用法中,模板方法使用子类来提供不同的行为。使用策略,您注入一个算法对象。在您的示例中,模板(分离) 和策略之间没有有用的区别。考虑到 Gamma 等人书的年龄,介绍此当您与其他程序员交谈时,如果没有充分解释新术语的差异,很可能会引起混乱。避免在课程之外使用它。
模板允许您访问基类中的受保护成员。策略允许您开发与使用它们的对象更加松散耦合的算法,并允许您将相同的算法注入到许多不同类型的对象中。
In common usage, Template method uses subclasses to provide the varied behaviours. With Strategy, you inject an algorithm object. In your example, there is no useful distinction between Template (separation) and Strategy. Given the age of the Gamma et al book, introducing this new terminology withou adequately explaining the difference is likely to simply cause confusion when you talk to other programmers. Avoid using it outside your lessons.
Template allows you to access protected members in the base class. Strategy allows you to develop you algorithms more losely coupled from the objects that use them, and allows you to inject the same algorithm into many different types of object.
模板方法:
策略模式:
基本差异。
看看 Journaldev 模板方法 和 策略文章,以便更好地理解 sourcemaking 文章。
Template Method:
Strategy pattern:
Basic differences.
Have a look at Journaldev Template method and Strategy articles for better understanding along with sourcemaking articles.