Reputation: 2856
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:
Which of the two is a more correct way of using memory for the State Pattern? (or another alternative to these 2)
Thanks
Upvotes: 4
Views: 591
Reputation: 559
Implement the State pattern alongside a variation of the Memento pattern?
Upvotes: 0
Reputation: 18570
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.
Upvotes: 1
Reputation: 158454
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.
Upvotes: 0
Reputation: 1047
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.
Upvotes: 3
Reputation: 799100
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.
Upvotes: 2