战略设计模式和国家设计模式之间的区别是什么?我在网上浏览了不少文章,但看不出明显的区别。
有人能用外行的语言解释一下吗?
战略设计模式和国家设计模式之间的区别是什么?我在网上浏览了不少文章,但看不出明显的区别。
有人能用外行的语言解释一下吗?
当前回答
“策略”只是一种算法,你可以根据自己的需要在不同的情况下改变它,它为你处理一些事情。 例如,你可以选择如何压缩一个文件。Zip or rar…在一个方法中。
但是“状态”可以改变你所有的对象行为,当它改变时, 甚至它也能改变其他领域……这就是为什么它有一个指向它的主人的引用。您应该注意到,改变对象字段完全可以改变对象行为。 例如,当你在obj中将stat0更改为State1时,你将一个整数更改为10。因此,当我们调用obj.f0()进行一些计算并使用该整数时,它会影响结果。
其他回答
策略:策略是固定的,通常由几个步骤组成。(排序只构成了一个步骤,因此是一个非常糟糕的例子,因为它太原始了,无法理解此模式的目的)。 策略中的“主”例程调用了一些抽象方法。如。“进入房间策略”,“main-method”是goThroughDoor(),它看起来像:approachDoor(), if (locked()) openLock();openDoor ();enterRoom ();把();closeDoor ();if (wasLocked()) lockDoor();
现在,这个通用“算法”的子类可以实现该算法的步骤,该算法用于通过可能锁着的门从一个房间移动到另一个房间。
换句话说,策略子类化不会改变基本算法,只会改变单个步骤。
上面是一个模板方法模式。现在把属于一起的步骤(解锁/锁定和打开/关闭)放到它们自己的实现对象中,并委托给它们。例如,带钥匙的锁和带码卡的锁是两种锁。将策略委托给“Step”对象。现在您有了一个策略模式。
状态模式是完全不同的东西。
你有一个包装对象和被包装的对象。被包装的是“状态”。状态对象只能通过它的包装器访问。现在您可以随时更改包装对象,因此包装器似乎可以更改其状态,甚至更改其“类”或类型。
E.g. you have a log on service. It accepts a username and a password. It only has one method: logon(String userName, String passwdHash). Instead of deciding for itself whether a log on is accepted or not, it delegates the decision to a state object. That state object usually just checks if the user/pass combination is valid and performs a log on. But now you can exchange the "Checker" by one that only lets priviledged users log on (during maintanace time e.g.) or by one that lets no one log on. That means the "checker" expresses the "log on status" of the system.
最重要的区别是:当你选择了一种策略,你要坚持它,直到你完成它。这意味着你调用它的“主方法”,只要它在运行,你就永远不会改变策略。OTOH在系统运行时的状态模式情况下,您可以随意更改您认为合适的状态。
策略表示“做”某事的对象,具有相同的开始和结束结果,但内部使用不同的方法。在这个意义上,它们类似于表示动词的实现。状态模式OTOH使用的对象“是”某种东西——操作的状态。虽然它们也可以表示对该数据的操作,但它们更类似于名词的表示,而不是动词的表示,并且是为状态机定制的。
差异在http://c2.com/cgi/wiki?StrategyPattern中讨论。我使用Strategy模式允许在分析数据的总体框架中选择不同的算法。通过这种方式,您可以添加算法,而不必更改整个框架及其逻辑。
一个典型的例子是你有一个优化函数的框架。框架设置数据和参数。策略模式允许您在不改变框架的情况下选择算法,如最快速下降、共轭梯度、BFGS等。
简而言之,使用策略模式,我们可以动态地设置一些行为,使用状态模式,我们可以确定,对象将随着状态的变化而在内部改变其行为。
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.