状态设计模式中的转换方法
我有一个状态机,有许多状态A--B--C--D--E
。如果某些条件得到验证,我有很多从 C
到 A
的转换。对于每个状态,我都有一个扩展抽象类 State 的类,并且有一个管理器将每个转换方法委托给状态方法。问题是“状态可以直接调用管理器转换方法吗?”。我在互联网上只看到过一些例子,其中有一个主类确切地知道转换发生了多少次(即 insertQuarter()
、ejectQuarter()
、turnCrank ()
、分配()
)。 我发现做到这一点的唯一方法是调用状态中的管理器转换方法。这是错误的还是不好的做法?
提前致谢 托比亚
I have a state machine with many states A--B--C--D--E
. I have many transitions from C
for example to A
if some condition is verified. For every state I have a class extending abstract class State
and I have a manager that delegates every transition method to state method. The question is "could states call directly manager transition methods?". I have seen on Internet only examples in which there is a main class that knows exactly how many times transition happens (i.e. insertQuarter()
, ejectQuarter()
, turnCrank()
, dispense()
).
The only way I found to do this is to call manager transition methods in states. Is this wrong or bad practice?
Thanks in advance
Tobia
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要一个简单的同步状态机,其中在任何给定时间点最多发生一次执行,我想到的模型如下:
1)执行的上下文由 Context 对象表示。上下文在状态之间传递,并由管理器用于流程决策。上下文的 API 取决于您需要系统的通用程度。
2)State接口包含execute(Context)方法,具体逻辑发生在该方法中。允许使用和更改上下文数据。
3) 管理器配置转换规则。给定最后一个状态和上下文,它能够确定下一个要执行的状态。它首先执行初始状态。每次执行状态 S 后,它都会根据与状态 S 关联的转换规则检查上下文对象。当它到达最终状态时,流程结束。
通过这种设计,状态实现不会以任何方式了解管理器,并且不参与路由决策。
If you need a simple synchronous state machine, where at most one execution takes place at any given point in time, the model I'm thinking of is as follows:
1) A context of the execution is represented by a Context object. The context is passed between the states, and it is used for flow decisions by the manager. The API of the context depends on how generic you need the system to be.
2) State interface contains the execute(Context) method, where the specific logic takes place. It is allowed to use and change the context data.
3) The manager is configured with the transition rules. It is able of determining the next state to execute, given the last state and the context. It starts by executing the initial state. After each execution of state S it checks the context object against the transition rules associated with the state S. When it reaches a terminal state, the flow is over.
With this design, the state implementations are not aware of the manager in any way, and are not involved in routing decisions.
是的......至少如果我正确理解你的问题的话。
管理器必须保留对当前状态的引用,因此当前状态必须能够要求管理器移动到下一个当前状态。请参阅 维基百科示例 作为示例。
Yes... At least if I understood your question correctly.
The manager has to keep a reference to the current state, so the current state must be able to ask the manager to move to the next current state. Look at the Wikipedia example for an example.