战略设计模式和国家设计模式之间的区别是什么?我在网上浏览了不少文章,但看不出明显的区别。
有人能用外行的语言解释一下吗?
战略设计模式和国家设计模式之间的区别是什么?我在网上浏览了不少文章,但看不出明显的区别。
有人能用外行的语言解释一下吗?
当前回答
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模式处理对象(处于)什么(状态或类型)——它封装了依赖状态的行为,而 策略模式处理对象如何执行特定任务——它封装了一个算法。
然而,实现这些不同目标的结构非常相似;这两种模式都是带有委托的组合示例。
关于它们的优点:
通过使用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.
“策略”只是一种算法,你可以根据自己的需要在不同的情况下改变它,它为你处理一些事情。 例如,你可以选择如何压缩一个文件。Zip or rar…在一个方法中。
但是“状态”可以改变你所有的对象行为,当它改变时, 甚至它也能改变其他领域……这就是为什么它有一个指向它的主人的引用。您应该注意到,改变对象字段完全可以改变对象行为。 例如,当你在obj中将stat0更改为State1时,你将一个整数更改为10。因此,当我们调用obj.f0()进行一些计算并使用该整数时,它会影响结果。
状态在状态派生类中有一点依赖关系:就像一个状态知道接下来的其他状态。例如,对于任何季节状态,夏天在冬天之后,或者对于购物,交付状态在存款状态之后。
另一方面,策略没有这样的依赖关系。在这里,任何类型的状态都可以基于程序/产品类型进行初始化。
策略模式涉及到将算法的实现从宿主类移到单独的类中。这意味着宿主类不需要提供每个算法本身的实现,这很可能导致不干净的代码。
排序算法通常被用作一个例子,因为它们都做同样的事情(排序)。如果将每个不同的排序算法放入自己的类中,那么客户机可以轻松地选择使用哪种算法,并且模式提供了访问算法的简单方法。
状态模式涉及当对象的状态发生变化时改变对象的行为。这意味着宿主类不需要为它可能处于的所有不同状态提供行为的实现。宿主类通常封装提供给定状态下所需功能的类,并在状态改变时切换到不同的类。