真正的策略设计模式请站起来吗? [英] Will the real strategy design pattern please stand up?

查看:163
本文介绍了真正的策略设计模式请站起来吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与某人的战斗模式真的是一个怪异的战斗,我需要一点专家的帮助(阅读:确定的证明)。

I had a geek fight with someone over what the strategy pattern really is and I need a little expert help (read: definitive proof).

我们都同意策略模式允许在运行时交换类的内容(例如行为),同时保持相同的界面。然而,她的论点是为了算法成为一种策略,你必须得到相同的结果。我的论点是,交换一个算法或一个类的逻辑可能意味着重写操作的结果是不同的,但它仍然符合策略模式的目的,意图(和分类)。

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.

她的代码示例与评论:

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

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天全站免登陆