谁能给我解释一下模板方法模式和策略模式的区别是什么?
据我所知,它们99%是一样的——唯一的区别是 模板方法模式有一个抽象类作为基础 类,而策略类使用已实现的接口 由每个具体的策略类。
然而,就客户端而言,它们是以完全相同的方式被消费的——这是正确的吗?
谁能给我解释一下模板方法模式和策略模式的区别是什么?
据我所知,它们99%是一样的——唯一的区别是 模板方法模式有一个抽象类作为基础 类,而策略类使用已实现的接口 由每个具体的策略类。
然而,就客户端而言,它们是以完全相同的方式被消费的——这是正确的吗?
当前回答
继承与聚合(is-a与has-a)。这是实现同一目标的两种方法。
这个问题显示了选择之间的一些权衡:继承还是聚合
其他回答
我建议你读一下这篇文章。它解释了一个实际案例的差异。
引用自文章
"As one can see implementing classes also depend upon the template method class. This dependency causes to change the template method if one wants to change some of the steps of the algorithm. On the other side strategy completely encapsulates the algorithm. it gives the implementing classes to completely define an algorithm. Therefore if any change arrives one does need to change the code for previously written classes. This was the primary reason I choose strategy for designing up the classes. One feature of template method is that template method controls the algorithm. Which can be a good thing in other situation but in my problem this was restricting me to design the classes. On the other side strategy does not control the steps of an algorithm which enables me to add completely different conversion methods. Hence in my case strategy helps me for implementation. One drawback of strategy is that there is too much code redundancy and less code sharing. As it is obvious in the presented example of this article I have to repeat the same code in four classes again and again. Therefore it is hard to maintain because if the implementation of our system such as step 4 which is common to all is changed then I will have to update this in all 5 classes. On the other side, in template method, I can only change the superclass and the changes are reflected into the sub classes. Therefore template method gives a very low amount of redundancy and high amount of code sharing among the classes. Strategy also allows changing the algorithm at run-time. In template method one will have to re-initialize the object. This feature of strategy provide large amount of flexibility. From design point of view one has to prefer composition over inheritance. Therefore using strategy pattern also became the primary choice for development."
继承与聚合(is-a与has-a)。这是实现同一目标的两种方法。
这个问题显示了选择之间的一些权衡:继承还是聚合
模板模式用于特定操作具有某些可以根据其他变化的原语行为定义的不变行为。抽象类定义了不变行为,而实现类定义了相关方法。
在策略中,行为实现是独立的——每个实现类定义行为,它们之间没有共享代码。两者都是行为模式,因此被客户以大致相同的方式消费。通常策略只有一个公共方法——execute()方法,而模板可以定义一组公共方法以及一组支持的私有原语,这些原语必须由子类实现。
这两种模式可以很容易地结合使用。您可能有一个策略模式,其中几个实现属于使用模板模式实现的策略家族。
我认为这两种模式的类图显示了差异。
策略 在类中封装算法 图片链接
模板方法 将算法的精确步骤推迟到子类 链接到图片
策略公开为接口,模板方法公开为抽象类。这通常在框架中被大量使用。 如。 Spring框架的MessageSource类是用于解析消息的策略接口。客户端使用该接口的特定实现(策略)。
和相同接口AbstractMessageSource的抽象实现,AbstractMessageSource具有解析消息的通用实现,并公开了resolveCode()抽象方法,以便子类可以以自己的方式实现它们。AbstractMessageSource是模板方法的一个例子。
http://docs.spring.io/spring/docs/4.1.7.RELEASE/javadoc-api/org/springframework/context/support/AbstractMessageSource.html