Java开发人员必须清楚地了解 Core Java应用程序中状态和策略设计模式之间的区别,以便正确使用它们。
- State 和 Strategy 设计模式虽然结构相似,都基于 Open Closed 设计原则,代表 SOLID 设计原则中的“O”,但它们的意图完全不同。
- Java的策略设计模式用于封装一组相关的算法,为客户端提供运行时灵活性。客户端可以在运行时选择任何算法,而无需更改使用 Strategy 对象的 Context 类。
- 策略模式的一些流行示例是编写代码,它使用算法,例如加密、压缩或排序算法。
现在可以清楚地看到 Strategy 和 State 模式之间的区别,它们的意图是不同的。状态模式帮助对象管理状态,而策略模式允许客户端选择不同的行为。另一个不容易看到的区别是,谁推动了行为的改变。
在策略模式的情况下,它是客户端,它提供了与上下文不同的策略,在状态模式中,状态转换由上下文或状态本身管理。此外,如果您在 State 对象本身中管理状态转换,则它必须持有上下文的引用,以便它可以调用setState()方法来更改 Context 的当前状态。自动售货机是最受欢迎的例子之一。
到目前为止,我们注意到状态和策略在结构上是相似的,它们的意图是不同的。因此,以下是Java状态和策略设计模式之间的主要主要区别,它们在它们的类中看起来都很相似,它们都执行开放封闭设计原则并封装行为。使用 Strategy 设计模式,封装算法或策略,在运行时提供给 Context,可能作为参数或组合对象,并使用 State Pattern 管理Java的状态转换。
STATE PATTERN | STRATEGY PATTERN |
---|---|
In-State pattern, an individual state can contain the reference of Context, to implement state transitions. | But Strategies doesn’t contain the reference of Context, where they are used. |
State encapsulate state of an Object. | While Strategy Pattern encapsulates an algorithm or strategy. |
State pattern helps a class to exhibit different behaviors in a different state. | Strategy Pattern encapsulates a set of related algorithms and allows the client to use interchangeable behaviors through composition and delegation at runtime. |
The state is part of the context object itself, and over time, the context object transitions from one State to another. | It can be passed as a parameter to there the Object which uses them e.g. Collections.sort() accepts a Comparator, which is a strategy. |
State Pattern defines the “what” and “when” part of an Object. Example: What can an object when it’s in a certain state. | Strategy pattern defines the “How” part of an Object. Example: How a Sorting object sorts data. |
Order of State transition is well-defined in State pattern. | There is no such requirement for a Strategy pattern. The client is free to choose any Strategy implementation of his choice. |
Change in State can be done by Context or State object itself. | Change in Strategy is done by the Client. |
Some common examples of Strategy Patterns are encapsulating algorithms e.g. sorting algorithms, encryption algorithms, or compression algorithms. | On the other hand, recognizing the use of State design patterns is pretty easy. |
If you see, your code needs to use different kinds of related algorithms, then think of using a Strategy pattern. | If you need to manage state and state transition, without lots of nested conditional statements, state pattern is the pattern to use. |