带记忆的状态模式
我在正常状态机中使用状态模式。我希望能够从 [A -> B],[B -> C],和[A -> C]。 现在我们的域有了新规则,现在我需要从 [C -> A]也可以,但前提是如果我以前从未去过B。 所以我们有带有记忆的状态。有两种可能的解决方案:
- 创建一个新的状态 CB ,这意味着 B 之后的 C,并具有这些规则 [A -> B],[B -> CB],[A -> C],[C -> A]
- 使用这样一个事实:我们的 Context 有一个包含先前状态的列表(我们称之为 StateHistoric)和进行转换的日期(状态历史记录也是我们客户的域要求),然后使用这些规则 [A -> B],[B -> C],[A -> C],[C ->如果 Context.StateHistoric 中 B 不是,则为 A]。
对于状态模式来说,这两种方式中哪一种更正确地使用内存? (或这 2 个的其他替代方案)
谢谢
I was using State Pattern in a normal state machine. I wanted to be able to go from [A -> B], [B -> C], and [A -> C].
Now our domain has a new rule, now i need to go from [C -> A] also,but only if i have never been in B before.
So we have states with memory. There are two possible solutions:
- Create a new State CB wich means C after B, and have these rules [A -> B], [B -> CB], [A -> C], [C -> A]
- Use the fact that our Context has a list with the previous states (lets call it StateHistoric) and the date when the transitions were made (the state history is also a domain requirement of our customer), and then use these rules [A -> B], [B -> C], [A -> C], [C -> A if B IS NOT in Context.StateHistoric].
Which of the two is a more correct way of using memory for the State Pattern? (or another alternative to these 2)
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
寻求第二个解决方案。它更容易理解,也更容易扩展。
不要仅仅因为设计模式的名字听起来与你喜欢做的类似而费心去遵守它。
Go for the second solution. It's easier to understand and easier to extend.
Don't bother adhering to the design pattern just because its name sounds similar to what you like to do.
如果它有内存,那么它就不是真正的状态机。如果您想保持这一身份,选项 1 是正确的选择。
If it has memory then it's not a true state machine. Option 1 is the correct one if you want to maintain this identity.
带记忆的状态机确实存在,它们被称为下推自动机......
这个想法是有一个堆栈,您可以读取该堆栈进入某个状态并写入退出该状态。
关于状态设计模式,我想它可以作为上下文中的备忘录来实现。
State machines with memory do exist, they are called pushdown automata...
The idea is to have a stack which you can read getting to a state and write getting out of the state.
In regards to state design pattern, I guess it could be implemented as a Memento in context.
选项#2 有效。您的历史列表有多大?如果搜索列表成为一个漫长的过程,那么我会选择选项#3:向上下文中添加一个布尔标志,称为“visitedStateB”。在初始化时将此标志设置为 false。当转换带您进入状态 B 时,将标志设置为 true。
Option #2 works. How big is your history list? If searching through the list becomes a lengthy process, then I'd go with Option #3: Add a boolean flag to your context called something like visitedStateB. Set this flag to false in initialization. Set the flag true when a transition takes you into state B.
与 Memento 模式 的变体一起实现状态模式吗?
Implement the State pattern alongside a variation of the Memento pattern?