战略设计模式的确切定义是什么? [英] What is the exact definition of the strategy design pattern?

查看:89
本文介绍了战略设计模式的确切定义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与某人就战略模式的真实性进行了极客的斗争,我需要专家来解决此问题.

I had a geek fight with someone over what the strategy pattern really is and I need a expert to settle the matter.

我们都同意策略模式允许在运行时交换类的胆量(例如行为),同时保持相同的接口.但是,她的论点是要使[算法]成为一种策略,您必须获得相同的结果".我的争论是交换一个类的算法"或逻辑可能意味着被覆盖的操作的结果是不同的,但它仍然符合策略模式的目的,意图(和分类).

We both agree that the strategy pattern allows for the guts of a class (e.g., the behavior) to be swapped out at runtime while maintaining the same interface. However, her contention is that "For [the algorithms] to be a strategy, You would have to get the same results". My contention is that swapping an "algorithm" or logic of a class could mean that the results of the overridden operation are different, but that it still meets the purpose, intent (and classification) of the strategy pattern.

带有注释的她的代码示例:

Her code example with comments:

根据您的定义,一个类的任何子类都是一种策略.它们具有相同的方法定义(签名),因此可以互换.

By your definition, any subclasses of a class would be a strategy. They have the same method definitions (signatures), and are therefore interchangeable.

Interface Strategy
{
    DoArithmatic(int[] a)
}

Class A : Strategy
public int DoArithmatic(int[]a)
{
     int temp = 0;
     for(int i =0; i< a.length; i++)
          temp += a[i]
}

Class B : Strategy
public int DoArithmaticB(int[]a)
{
     int temp = 0;
     for(int i =a.length -1; i>-1; i--)
          temp += a[i]
}

Class C : Strategy
public int DoArithmatic(int[]a)
{
     int temp = 0;
     for(int i =0; i< a.length; i++)
          temp -= a;
}

int[] a = { 1,2,3 }
ClassA.DoArithmatic(a) = 6
ClassB.DoArithmatic(a) = 6
ClassC.DoArithmatic(a) = -6//This one is not interchangeable

前两个是策略.因为对于任何输入,他们都会为您提供完全相同的答案.最后一个不是.仅仅因为它给您一个int并不能使它成为一种策略.他们必须做"同样的事情.

The first two are strategies. Because for any input they will give you the EXACT same answer. the last one is not. Just because it gives you an int does not make it a strategy. They have to "DO" the same thing.

您不能仅使用更高"的抽象术语来使它们成为一种策略.

You can't use a "higher" abstraction term just to make them a strategy.

这些都做"MATH",但是他们并不是都以不同的方式做相同"的事情.这就是策略的本质.

These all do "MATH" but they are not all doing the "same" thing in a different way. That is the essence of a strategy.

那么,谁是对的?

推荐答案

您是正确的,您的同事需要阅读GoF.

You sir are correct and your coworker needs to read the GoF.

策略模式可让算法独立于使用它们的客户端而变化."

"The strategy pattern lets the algorithms vary independently from clients that use them."

请参阅:

http://www.dofactory.com/Patterns/PatternStrategy.aspx

这篇关于战略设计模式的确切定义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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