State Pattern with Memory
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开发者_如何学JAVA 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
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.
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.
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.
Implement the State pattern alongside a variation of the Memento pattern?
精彩评论