模板方法与策略模式有什么区别? [英] What is the difference between the template method and the strategy patterns?

查看:1094
本文介绍了模板方法与策略模式有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释模板方法模式和策略模式之间有什么区别?



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



但是,就客户端而言,它们的使用方式完全相同 - 这是否正确?

解决方案

两者之间的主要区别是选择具体算法时。



使用模板方法模式,这种情况发生在编译时通过子类化模板。每个子类通过实现模板的抽象方法提供了一个不同的具体算法。当客户端调用模板的外部接口的方法时,模板根据需要调用其抽象方法(其内部接口)来调用算法。

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

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

virtual void DoAlgorithm()= 0; //抽象
}

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

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

类策略
{
策略(IA算法算法){...}

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



总结:




  • 模板方法模式:编译时算法选择子类

  • 策略模式: strong>运行时算法选择遏制


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 - the only difference being that the template method pattern has an abstract class as the base class whereas the strategy class uses an interface that is implemented by each concrete strategy class.

However, as far as the client is concerned they are consumed in exactly the same way - is this correct?

解决方案

The main difference between the two is when the concrete algorithm is chosen.

With the Template method pattern this happens at compile-time by subclassing the template. Each subclass provides a different concrete algorithm by implementing the template's abstract methods. When a client invokes methods of the template's external interface the template calls its abstract methods (its internal interface) as required to invoke the algorithm.

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

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

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

In contrast, the Strategy pattern allows an algorithm to be chosen at runtime by containment. The concrete algorithms are implemented by separate classes or functions which are passed to the strategy as a parameter to its constructor or to a setter method. Which algorithm is chosen for this parameter can vary dynamically based on the program's state or inputs.

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

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

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

In summary:

  • Template method pattern: compile-time algorithm selection by subclassing
  • Strategy pattern: run-time algorithm selection by containment

这篇关于模板方法与策略模式有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆