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

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


当前回答

策略表示“做”某事的对象,具有相同的开始和结束结果,但内部使用不同的方法。在这个意义上,它们类似于表示动词的实现。状态模式OTOH使用的对象“是”某种东西——操作的状态。虽然它们也可以表示对该数据的操作,但它们更类似于名词的表示,而不是动词的表示,并且是为状态机定制的。

其他回答

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模式中,这些派生类才保留对上下文类的引用。

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

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

状态在状态派生类中有一点依赖关系:就像一个状态知道接下来的其他状态。例如,对于任何季节状态,夏天在冬天之后,或者对于购物,交付状态在存款状态之后。

另一方面,策略没有这样的依赖关系。在这里,任何类型的状态都可以基于程序/产品类型进行初始化。

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

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.

策略模式涉及到将算法的实现从宿主类移到单独的类中。这意味着宿主类不需要提供每个算法本身的实现,这很可能导致不干净的代码。

排序算法通常被用作一个例子,因为它们都做同样的事情(排序)。如果将每个不同的排序算法放入自己的类中,那么客户机可以轻松地选择使用哪种算法,并且模式提供了访问算法的简单方法。

状态模式涉及当对象的状态发生变化时改变对象的行为。这意味着宿主类不需要为它可能处于的所有不同状态提供行为的实现。宿主类通常封装提供给定状态下所需功能的类,并在状态改变时切换到不同的类。