Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

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/

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top