战略设计模式和国家设计模式之间的区别是什么?我在网上浏览了不少文章,但看不出明显的区别。
有人能用外行的语言解释一下吗?
战略设计模式和国家设计模式之间的区别是什么?我在网上浏览了不少文章,但看不出明显的区别。
有人能用外行的语言解释一下吗?
当前回答
这两种模式都用于改变对象的行为,
按照设计,状态模式对象只有一个状态,对象的行为基于实现的单个状态(类)及其子类。
相反,策略没有单一的状态,对象的行为是由不同策略对象的实现决定的。
其他回答
策略表示“做”某事的对象,具有相同的开始和结束结果,但内部使用不同的方法。在这个意义上,它们类似于表示动词的实现。状态模式OTOH使用的对象“是”某种东西——操作的状态。虽然它们也可以表示对该数据的操作,但它们更类似于名词的表示,而不是动词的表示,并且是为状态机定制的。
差异在http://c2.com/cgi/wiki?StrategyPattern中讨论。我使用Strategy模式允许在分析数据的总体框架中选择不同的算法。通过这种方式,您可以添加算法,而不必更改整个框架及其逻辑。
一个典型的例子是你有一个优化函数的框架。框架设置数据和参数。策略模式允许您在不改变框架的情况下选择算法,如最快速下降、共轭梯度、BFGS等。
战略模式和状态模式具有相同的结构。如果您查看两种模式的UML类图,它们看起来完全相同,但是它们的意图完全不同。状态设计模式用于定义和管理对象的状态,而策略模式用于定义一组可互换的算法,并让客户选择其中之一。因此,策略模式是客户端驱动的模式,而对象可以管理自己的状态。
这两种模式都用于改变对象的行为,
按照设计,状态模式对象只有一个状态,对象的行为基于实现的单个状态(类)及其子类。
相反,策略没有单一的状态,对象的行为是由不同策略对象的实现决定的。
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.