状态设计模式中的过渡方法 [英] Transition methods in state design pattern

查看:110
本文介绍了状态设计模式中的过渡方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个状态机,其中有许多状态A--B--C--D--E.如果已验证某些条件,则有很多从CA的过渡.对于每个状态,我都有一个扩展抽象类State的类,并且有一个将每个过渡方法委托给状态方法的管理器.问题是国家可以直接调用管理器转换方法吗?".我仅在Internet上看到过这样的示例,其中有一个主类确切地知道发生了多少次过渡(即insertQuarter()ejectQuarter()turnCrank()dispense()). 我发现做到这一点的唯一方法是在状态下调用管理器转换方法.这是错误的做法还是不好的做法?

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 Stateand 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?

先谢谢了 托比亚

推荐答案

如果您需要一个简单的同步状态机,该状态机最多在任何给定时间点执行一次,那么我考虑的模型如下:

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)执行的上下文由Context对象表示.上下文在状态之间传递,并由管理器用于流程决策.上下文的API取决于您需要系统的通用性.

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)状态接口包含execute(Context)方法,在该方法中发生特定的逻辑.允许使用和更改上下文数据.

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)管理器配置有转换规则.给定最后一个状态和上下文,它能够确定要执行的下一个状态.它从执行初始状态开始.在每次执行状态S后,它都会根据与状态S相关联的转换规则检查上下文对象.当到达终端状态时,流程结束.

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.

这篇关于状态设计模式中的过渡方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆