战略设计模式和国家设计模式之间的区别是什么?我在网上浏览了不少文章,但看不出明显的区别。
有人能用外行的语言解释一下吗?
战略设计模式和国家设计模式之间的区别是什么?我在网上浏览了不少文章,但看不出明显的区别。
有人能用外行的语言解释一下吗?
当前回答
当你有一个可以分为两个任务的项目时:
任务1:您可以使用两种不同的算法之一来完成:alg1, alg2
任务2:您可以使用三种不同的算法之一来完成:alg3, alg4, alg5
Alg1和alg2是可互换的;Alg3、alg4和alg5是可以互换的。
在任务1和任务2中选择哪种算法取决于状态:
状态1:任务1中需要alg1,任务2中需要alg3
状态2:任务1中需要alg2,任务2中需要alg5
上下文可以将状态对象从状态1更改为状态2。然后,您的任务将由alg2和alg5完成,而不是alg1和alg3。
您可以为任务1或任务2添加更多可互换的算法。这就是战略模式。
你可以在任务1和任务2中使用不同的算法组合获得更多的状态。状态模式允许从一种状态切换到另一种状态,并执行不同的算法组合。
其他回答
老实说,这两种模式在实践中非常相似,它们之间的定义差异往往取决于你问谁。一些流行的选择是:
状态存储对包含它们的上下文对象的引用。战略则不然。 状态可以替换自己(IE:将上下文对象的状态更改为其他状态),而策略则不能。 策略作为参数传递给上下文对象,而状态由上下文对象本身创建。 策略只处理一个特定的任务,而状态为上下文对象所做的所有(或几乎所有)事情提供底层实现。
一个“经典”的实现将匹配列表中的每个道具的状态或策略,但你也会遇到混合了两者的情况。具体是国家层面的还是战略层面的,最终是一个主观问题。
策略模式涉及到将算法的实现从宿主类移到单独的类中。这意味着宿主类不需要提供每个算法本身的实现,这很可能导致不干净的代码。
排序算法通常被用作一个例子,因为它们都做同样的事情(排序)。如果将每个不同的排序算法放入自己的类中,那么客户机可以轻松地选择使用哪种算法,并且模式提供了访问算法的简单方法。
状态模式涉及当对象的状态发生变化时改变对象的行为。这意味着宿主类不需要为它可能处于的所有不同状态提供行为的实现。宿主类通常封装提供给定状态下所需功能的类,并在状态改变时切换到不同的类。
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.
简而言之,使用策略模式,我们可以动态地设置一些行为,使用状态模式,我们可以确定,对象将随着状态的变化而在内部改变其行为。
当一个特定的任务有多个算法,而客户端决定在运行时使用的实际实现时,使用策略模式。
来自wiki策略模式文章的UML图:
主要特点:
这是一种行为模式。 它是基于委派的。 它通过修改方法行为来改变对象的内容。 它用来在一系列算法之间切换。 它在运行时改变对象的行为。
参考这篇文章获得更多信息和现实世界的例子:
策略模式的真实例子
状态模式允许对象在其内部状态改变时改变其行为
来自wiki状态模式文章的UML图:
如果我们必须根据对象的状态来改变它的行为,我们可以在object中有一个状态变量,并使用If -else条件块来根据状态执行不同的操作。状态模式用于通过上下文和状态实现提供一种系统的、损失耦合的方式来实现这一点。
有关更多细节,请参阅这篇journaldev文章。
与资源制作和期刊开发文章的主要区别:
The difference between State and Strategy lies with binding time. The Strategy is a bind-once pattern, whereas State is more dynamic. The difference between State and Strategy is in the intent. With Strategy, the choice of algorithm is fairly stable. With State, a change in the state of the "context" object causes it to select from its "palette" of Strategy objects. Context contains state as instance variable and there can be multiple tasks whose implementation can be dependent on the state whereas in strategy pattern strategy is passed as argument to the method and context object doesn’t have any variable to store it.