状态模式是否准确地代表了该方法?
我从状态模式s<的典型实现中收集到的信息/b> 是这样的:
问题: 表示一个对象 O,其行为根据其当前状态而改变。
解决方案:
1. 让S,这个对象O内部的另一个对象,代表状态
2. 对象S将调用O
的适当操作 3. 对象S将决定对象O的下一个状态
我主要关心的是#3
。状态转换表基本上分布在所有状态上。我发现这些解决方案变得难以快速管理。这些状态不是指示器,而是包含太多有关状态机的信息。
尽管 #2
困扰着我,但我认为这是相当合理的(摩尔机。)我看到的唯一问题是在错误修复/调试过程中出现的:代码导航/理解变得困难,直到将所有状态映射提交到内存为止。
下面的实现会更精确吗?
将状态表示为枚举,对象根据枚举所持有的值决定操作。状态转换位于表(δ,状态转换函数)中,该表是当前状态到下一个状态的映射。这个状态转换表
还保存要执行的操作(Mealy machine )
What I gather from typical implementation of State patterns is this:
Problem: Represent an object O, whose behavior alters based on its current state.
Solution:
1. Let S, another object inside this object O, represent state
2. The object S will invoke the appropriate operation of O
3. The object S will decide the next state for the object O
My concern is primarily with #3
. The state transition table is essentially spread across all the states. I have seen these solutions become cumbersome to manage very quickly. Instead of being indicator, these states hold too much information about the state machine.
Even though #2
bothers me, I guess it is fairly reasonable (Moore machine.) The only issue I have seen arises during bug fixing/debugging: code navigation/understanding becomes difficult until one commits all the state mappings to memory.
Would the following implementation be more precise?
Represent states as enumerations, and the object decides the action based on the value held by the enumeration. The state transitions
are in a table (δ, a state transition function) that is a map of current state to next state. This state transition table
also holds the action to be performed (Mealy machine)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道你为什么认为状态模式只能代表摩尔机。
我们根据状态 (SleepingState) 和事件 (alarm) 选择输出 (kick_alarm_clock),这使其成为 Mealy 机器。
您的替代方案确实有效且受欢迎(还有其他替代方案)。由于几种方法都足以实现机器逻辑,因此您可以根据“设计”或个人品味的其他考虑因素做出决定。选择状态模式的设计原因可能是,如果您认为经常会添加新状态,或者某些状态看起来足够相似以保证继承关系。我倾向于选择美观:只有当机器相当密集时我才使用状态模式 - 即有不平凡的动作和动作。大多数 { state, event } 对的转换。如果机器相当稀疏,我会对所有空方法感到尴尬。
I don't know why you suppose that the State pattern can only represent Moore machines.
We chose our output (kick_alarm_clock) based on both the state (SleepingState) and the event (alarm), which makes it a Mealy machine.
Your alternative is indeed valid and popular (and there are others). Since several approaches are all sufficient to implement the machine logic, you make the decision based on other considerations of 'design' or personal taste. Design reasons to prefer the State pattern might be if you think you will often be adding new states, or if some states seem similar enough to warrant an inheritance relationship. I tend to choose on aesthetics: I use the State pattern only if the machine is fairly dense - i.e. there are nontrivial actions & transitions for most { state, event } pairs. If the machine is fairly sparse, I get embarrassed by all the empty methods.