Memento design pattern and State design pattern
Asked Answered
Q

3

6

Memento design pattern is used for restoring objects to previous state, like undo. But we can do undo and redo multiple times. I have read articles multiple times but still unclear to me as to are they similar or complement each other and can be used together.

Can State pattern be related to Memento Design pattern or be used together?

Quiteris answered 24/8, 2013 at 15:53 Comment(0)
G
3

The "state" in the "state pattern" is not the same kind of state that a memento pattern enables. A better name for the state pattern would be the "mode pattern". See this description of it for more details.

Now, one might use a memento to describe the state of an object that has a mode pattern involved, but that is the only particular relationship they have.

Gorki answered 24/8, 2013 at 19:51 Comment(2)
The link expiredMcwhirter
@Gorki please update description linkAdvanced
P
3

The "state" in the Memento is the state you save for later retrieval. It's something like a bookmark. For example, you can save a video position and then return to that position using the Memento pattern. (States are saved in the Caretaker participant.)

The "states" in the State Design pattern are like those found in state machines (or state engines). They act like a larger context where each state has a finite set of moves. So if you're in the "On" state, your options are to stay in the "On" state or change to the "Off" state. (State patterns do not have conditional statements!)

For PHP examples of both see:

http://www.php5dp.com/category/design-patterns/memento/

and

http://www.php5dp.com/category/design-patterns/state/

Parch answered 31/7, 2014 at 1:26 Comment(0)
D
2

To answer your first question, you can use memento to redo by making a second memento instance to store the "state" of the redo. However, depending how complicated the object's state is to be stored, it is often "cheaper" to use the Command Pattern to provide undo/redo functionality. The Command can be use to store only the changes to undo/redo while memento probably needs to store the entire state.

tallseth's answer is also correct that the "state" from the State Pattern is not the same "state" that memento stores.

Dori answered 26/8, 2013 at 2:0 Comment(1)
Actually, you would rather use both Command and Memento for undo/redo functionality: Command would then use Memento to maintain the state required for an undo/redo operation. See Rules of Thumb here.Wendeline

© 2022 - 2024 — McMap. All rights reserved.