谁能给我解释一下模板方法模式和策略模式的区别是什么?

据我所知,它们99%是一样的——唯一的区别是 模板方法模式有一个抽象类作为基础 类,而策略类使用已实现的接口 由每个具体的策略类。

然而,就客户端而言,它们是以完全相同的方式被消费的——这是正确的吗?


继承与聚合(is-a与has-a)。这是实现同一目标的两种方法。

这个问题显示了选择之间的一些权衡:继承还是聚合


模板模式用于特定操作具有某些可以根据其他变化的原语行为定义的不变行为。抽象类定义了不变行为,而实现类定义了相关方法。

在策略中,行为实现是独立的——每个实现类定义行为,它们之间没有共享代码。两者都是行为模式,因此被客户以大致相同的方式消费。通常策略只有一个公共方法——execute()方法,而模板可以定义一组公共方法以及一组支持的私有原语,这些原语必须由子类实现。

这两种模式可以很容易地结合使用。您可能有一个策略模式,其中几个实现属于使用模板模式实现的策略家族。


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

模板方法的例子:

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

这里你继承了application,并替换了init, run和done的操作。

策略的例子:

array.sort (IComparer<T> comparer)

在这里,当编写比较器时,您不继承数组。数组将比较算法委托给比较器。


不,它们的消费方式不一定相同。“模板方法”模式是为未来的实现者提供“指导”的一种方式。您告诉他们,“所有Person对象都必须有一个社会安全号码”(这是一个微不足道的例子,但它正确地传达了思想)。

策略模式允许在多个可能的实现之间切换。它(通常)不是通过继承实现的,而是通过让调用者传入所需的实现来实现的。例如,允许为ShippingCalculator提供几种不同的计算税收的方法之一(可能是NoSalesTax实现和PercentageBasedSalesTax实现)。

有时候,客户端会告诉对象使用哪种策略。就像在

myShippingCalculator.CalculateTaxes(myCaliforniaSalesTaxImpl);

但是客户端永远不会为基于模板方法的对象这样做。事实上,客户端甚至可能不知道对象是基于模板方法的。模板方法模式中的那些抽象方法甚至可能受到保护,在这种情况下,客户端甚至不知道它们的存在。


两者的主要区别在于具体算法的选择。

对于Template方法模式,这是在编译时通过子类化模板实现的。每个子类通过实现模板的抽象方法提供不同的具体算法。当客户端调用模板外部接口的方法时,模板会根据需要调用它的抽象方法(内部接口)来调用算法。

class ConcreteAlgorithm : AbstractTemplate
{
    void DoAlgorithm(int datum) {...}
}

class AbstractTemplate
{
    void run(int datum) { DoAlgorithm(datum); }

    virtual void DoAlgorithm() = 0; // abstract
}

相反,策略模式允许在运行时通过包含来选择算法。具体算法由单独的类或函数实现,这些类或函数作为参数传递给策略的构造函数或setter方法。为这个参数选择哪种算法可以根据程序的状态或输入动态变化。

class ConcreteAlgorithm : IAlgorithm
{
    void DoAlgorithm(int datum) {...}
}

class Strategy
{
    Strategy(IAlgorithm algo) {...}

    void run(int datum) { this->algo.DoAlgorithm(datum); }
}

总而言之:

模板方法模式:通过子类化来选择编译时算法 策略模式:通过包容选择运行时算法


我认为这两种模式的类图显示了差异。

策略 在类中封装算法 图片链接

模板方法 将算法的精确步骤推迟到子类 链接到图片


模板模式类似于策略模式。这两种模式在范围和方法上有所不同。

策略用于允许调用者改变整个算法,比如如何计算不同类型的税,而模板方法用于改变算法中的步骤。因此,策略的粒度更粗。模板允许在操作序列中进行细粒度的控制,但允许这些细节的实现有所不同。

另一个主要区别是策略使用委托,而模板方法使用继承。在Strategy中,算法被委托给主题将引用的另一个xxxStrategy类,但在Template中,您可以继承基类并重写方法来进行更改。

从http://cyruscrypt.blogspot.com/2005/07/template-vs-strategy-patterns.html


在策略模式中,子类起主导作用,它们控制算法。这里的代码是跨子类复制的。算法的知识和如何实现它分布在许多类中。

在模板模式中,基类具有算法。它最大化了子类之间的重用。由于算法在一个地方,基类保护它。


两者都非常相似,客户端代码以类似的方式使用它们。与上面最流行的答案不同,两者都允许在运行时选择算法。

The difference between the two is that while the strategy pattern allows different implementations to use completely different ways of the achieving the desired outcome, the template method pattern specifies an overarching algorithm (the "template" method) which is be used to achieve the result -- the only choice left to the specific implementations (sub-classes) are certain details of the said template method. This is done by having the the template method make call(s) to one or more abstract methods which are overridden (i.e. implemented) by the sub-classes, unlike the template method which itself is not abstract and not overridden by the sub-classes.

客户端代码使用抽象类类型的引用/指针调用模板方法,该引用/指针指向具体子类之一的实例,该实例可以在运行时确定,就像使用策略模式时一样。


我建议你读一下这篇文章。它解释了一个实际案例的差异。

引用自文章

"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."


模板方法:

它是基于继承的 定义了不能被子类改变的算法框架。只有某些操作可以在子类中被重写 父类完全控制算法,只与具体类的某些步骤不同 绑定在编译时完成

Template_method结构:

策略:

它基于委托/组合 它通过修改方法行为来改变对象的内容 它用来在一系列算法之间切换 它通过在运行时完全将一种算法替换为另一种算法来改变对象在运行时的行为 绑定在运行时完成

战略结构:

为了更好地理解,请查看Template方法和策略文章。

相关文章:

在JDK模板设计模式中,找不到一个方法定义了一组要按顺序执行的方法

策略模式的真实例子


模板模式:

模板方法是关于让子类重新定义算法的某些步骤,而不改变基类中定义的算法的主要结构和步骤。 模板模式通常使用继承,因此可以在基类中提供算法的泛型实现,如果需要,子类可以选择覆盖它。

public abstract class RobotTemplate {
    /* This method can be overridden by a subclass if required */
    public void start() {
        System.out.println("Starting....");
    }

    /* This method can be overridden by a subclass if required */
    public void getParts() {
        System.out.println("Getting parts....");
    }

    /* This method can be overridden by a subclass if required */
    public void assemble() {
        System.out.println("Assembling....");
    }

    /* This method can be overridden by a subclass if required */
    public void test() {
        System.out.println("Testing....");
    }

    /* This method can be overridden by a subclass if required */
    public void stop() {
        System.out.println("Stopping....");
    }

    /*
     * Template algorithm method made up of multiple steps, whose structure and
     * order of steps will not be changed by subclasses.
     */
    public final void go() {
        start();
        getParts();
        assemble();
        test();
        stop();
    }
}


/* Concrete subclass overrides template step methods as required for its use */
public class CookieRobot extends RobotTemplate {
    private String name;

    public CookieRobot(String n) {
        name = n;
    }

    @Override
    public void getParts() {
        System.out.println("Getting a flour and sugar....");
    }

    @Override
    public void assemble() {
        System.out.println("Baking a cookie....");
    }

    @Override
    public void test() {
        System.out.println("Crunching a cookie....");
    }

    public String getName() {
        return name;
    }
}

注意在上面的代码中,go()算法步骤总是相同的,但是子类可能为执行特定步骤定义不同的配方。

策略模式:

策略模式是指让客户端在运行时选择具体的算法实现。所有算法都是隔离且独立的,但是实现了一个公共接口,并且没有在算法中定义特定步骤的概念。

/**
 * This Strategy interface is implemented by all concrete objects representing an
 * algorithm(strategy), which lets us define a family of algorithms.
 */
public interface Logging {
    void write(String message);
}

/**
 * Concrete strategy class representing a particular algorithm.
 */
public class ConsoleLogging implements Logging {

    @Override
    public void write(String message) {
        System.out.println(message); 
    }

}

/**
 * Concrete strategy class representing a particular algorithm.
 */
public class FileLogging implements Logging {

    private final File toWrite;

    public FileLogging(final File toWrite) {
        this.toWrite = toWrite;
    }

    @Override
    public void write(String message) {
        try {
            final FileWriter fos = new FileWriter(toWrite);
            fos.write(message);
            fos.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }

}

要获得完整的源代码,请查看我的github存储库。


策略公开为接口,模板方法公开为抽象类。这通常在框架中被大量使用。 如。 Spring框架的MessageSource类是用于解析消息的策略接口。客户端使用该接口的特定实现(策略)。

和相同接口AbstractMessageSource的抽象实现,AbstractMessageSource具有解析消息的通用实现,并公开了resolveCode()抽象方法,以便子类可以以自己的方式实现它们。AbstractMessageSource是模板方法的一个例子。

http://docs.spring.io/spring/docs/4.1.7.RELEASE/javadoc-api/org/springframework/context/support/AbstractMessageSource.html


在此设计模式的模板方法中,子类可以覆盖一个或多个算法步骤,以允许不同的行为,同时确保仍然遵循总体算法(Wiki)。

模式名Template方法的意思是它是什么。假设我们有一个方法calculatessomething(),我们想要创建这个方法的模板。此方法将在基类中声明为非虚方法。假设这个方法是这样的。

CalculateSomething(){
    int i = 0;
    i = Step1(i);
    i++;
    if (i> 10) i = 5;
    i = Step2(i);
    return i;

} Step1和Step2方法实现可以由派生类给出。

在策略模式中,基类没有提供实现(这就是为什么基类实际上是类图中的接口)。

经典的例子是排序。根据需要排序的对象数量,创建适当的算法类(merge, bubble, quick等),并将整个算法封装在每个类中。

现在我们可以将排序实现为模板方法了吗?当然可以,但是您不会发现有太多/任何共性可以抽象出来并放置在基本实现中。因此,它违背了模板方法模式的目的。



相似之处

策略和模板方法模式之间有很多相似之处。策略和模板方法模式都可以用于满足开闭原则,并使软件模块易于扩展而无需更改其代码。这两种模式都表示通用功能与该功能的详细实现的分离。但是,它们在提供的粒度方面略有不同。


差异

以下是我在研究这两种模式时观察到的一些差异:

In Strategy, the coupling between the client and strategy is more loose whereas in Template Method, the two modules are more tightly coupled. In Strategy, mostly an interface is used though abstract class can also be used depending on the situation, and concrete class is not used whereas in Template method mostly abstract class or concrete class is used, interface is not used. In Strategy pattern, generally entire behaviour of the class is represented in terms of an interface, on the other hand, Template method is used for reducing code duplication and the boilerplate code is defined in base framework or abstract class. In Template Method, there can even be a concrete class with default implementation. In simple words, you can change the entire strategy (algorithm) in Strategy pattern, however, in Template method, only some things change (parts of algorithm) and rest of the things remain unchanged. In Template Method, the invariant steps are implemented in an abstract base class, while the variant steps are either given a default implementation, or no implementation at all. In Template method, the component designer mandates the required steps of an algorithm, and the ordering of the steps, but allows the component client to extend or replace some number of these steps.


图片取自微博客。


策略设计模式

支持组成。 为您提供在运行时更改对象行为的灵活性。 减少客户端代码和解决方案/算法代码之间的耦合。

模板方法设计模式

更喜欢继承而不是组合 在基类中定义算法。算法的各个部分可以在子类中定制。


我认为主要的区别是,有了模板,你需要一个算法来做一些事情,但让我们说,在算法的中间,你想要运行不同的行为,所以你可以发送一个接口的实现,使算法在运行时动态。

但是对于策略,你实际上有完全不同的算法执行而不仅仅是算法的一个变体,然后你选择运行哪个算法,但是模板你只有一个变体的算法。

最后,你可以实现你想要的,使用模板作为策略,反之亦然,但我看到了区别。


模板方法模式善于阐明算法的整体步骤,而策略模式适合灵活性和可重用性,因此如果需要,可以将策略组合在一起,例如:jdk8中的许多功能接口,如Comparator.reversed().那么比较(Comparator)是策略的一个角色。

模板方法模式侧重于更高的内聚性,而策略模式则与上下文对象松散耦合以分离关注点。

策略易于维护,因为上下文不知道具体的策略,无论主要算法在上下文中发生什么变化都不会影响策略。另一方面,如果在抽象模板类中改变算法的框架,可能会影响其子类的升级。


它们都是不同的技术来达到相同的结果,所以问题是在什么时候使用哪一种。

If you are using a framework or library which you do not have access to the source code and you want to change some behaviors of a class, so you have to go for Template Method. That means inheritance simply. If you are developing a class and it is obvious that some parts of the logic needs to be implemented differently to handle various situations, take the Strategy pattern. Strategy is more SOLID than the Template Method. It covers both Dependency Inversion and Open/Close principles. So it is extendable and also easily testable. If you are developing a class and you do not know what changes will happen in the future, divide your logic into separate and single responsible functions as much as possible. Just that. (Neither Template Method nor Strategy).