战略设计模式和国家设计模式之间的区别是什么?我在网上浏览了不少文章,但看不出明显的区别。

有人能用外行的语言解释一下吗?


当前回答

“策略”只是一种算法,你可以根据自己的需要在不同的情况下改变它,它为你处理一些事情。 例如,你可以选择如何压缩一个文件。Zip or rar…在一个方法中。

但是“状态”可以改变你所有的对象行为,当它改变时, 甚至它也能改变其他领域……这就是为什么它有一个指向它的主人的引用。您应该注意到,改变对象字段完全可以改变对象行为。 例如,当你在obj中将stat0更改为State1时,你将一个整数更改为10。因此,当我们调用obj.f0()进行一些计算并使用该整数时,它会影响结果。

其他回答

简而言之,使用策略模式,我们可以动态地设置一些行为,使用状态模式,我们可以确定,对象将随着状态的变化而在内部改变其行为。

不同之处在于它们解决的问题不同:

State模式处理对象(处于)什么(状态或类型)——它封装了依赖状态的行为,而 策略模式处理对象如何执行特定任务——它封装了一个算法。

然而,实现这些不同目标的结构非常相似;这两种模式都是带有委托的组合示例。


关于它们的优点:

通过使用State模式,状态保持(上下文)类不再知道它是什么状态或类型以及可用的状态或类型。这意味着类遵循开闭设计原则(OCP):类对状态/类型的更改是关闭的,但是状态/类型对扩展是开放的。

By using the Strategy pattern the algorithm-using (context) class is relieved from knowledge of how to perform a certain task (-- the "algorithm"). This case also creates an adherence to the OCP; the class is closed for changes regarding how to perform this task, but the design is very open to additions of other algorithms for solving this task. This likely also improves the context class' adherence to the single responsibility principle (SRP). Further the algorithm becomes easily available for reuse by other classes.

The Strategy pattern is really about having a different implementation that accomplishes (basically) the same thing, so that one implementation can replace the other as the strategy requires. For example, you might have different sorting algorithms in a strategy pattern. The callers to the object does not change based on which strategy is being employed, but regardless of strategy the goal is the same (sort the collection). The State pattern is about doing different things based on the state, while leaving the caller relieved from the burden of accommodating every possible state. So for example you might have a getStatus() method that will return different statuses based on the state of the object, but the caller of the method doesn't have to be coded differently to account for each potential state.

用外行的话来说,

在策略模式中,没有状态或所有状态相同。 每个人都有不同的方法来完成一项任务,就像不同的医生用不同的方法来治疗同一种疾病,同一种状态的同一病人。

在state Pattern中,主观上存在状态,如患者当前的状态(如高温或低温),据此决定下一步的行动(药物处方)。一个状态可以导致另一个状态,因此存在状态之间的依赖关系(技术上来说是组合)。

如果我们从技术上试图理解它,基于两者的代码比较,我们可能会失去情境的主观性,因为两者看起来非常相似。

这两种模式都委托给一个基类,这个基类有几个派生类,但是只有在State模式中,这些派生类才保留对上下文类的引用。

从另一个角度来看,战略模式是国家模式的简单版本;如果你愿意,也可以称之为子模式。这实际上取决于你是否希望派生状态保留对上下文的引用(即:你是否希望它们调用上下文上的方法)。

更多信息:Robert C Martin (& Micah Martin)在他们的书《c#中的敏捷原则、模式和实践》中回答了这个问题。(http://www.amazon.com/Agile-Principles-Patterns-Practices-C/dp/0131857258)