Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Memento and Command design pattern?

I have successfully coded a solitaire game on Java, and now I have been asked to implement an undo/redo on top of my design.

My plan was to store a list or stack of moves the user executed, and if the user wants to undo, I would 1. check if the user can undo (ie. there are moves in the list or stack), then 2. reverse the last two moves I stored (ie. the "from" move where I moved the card from and the "to" move, where I moved the card to).

For redo, I would just redo the moves, depending on how far down the user did the undo action (for example, if they pressed undo twice, I would be, at least, (size of list - 4) down my list or stack).

I think they will be implemented in an interface like so:

public interface UndoRedo {
    void undo();
    void redo();
 }

Am I implementing Memento, or Command design pattern, or neither? I'm having trouble grasping what the two design patterns look like in the context of an undo/redo for this game. I'm also a beginner with Java OOP, and design patterns in general.

like image 635
B.M. Corwen Avatar asked Dec 18 '22 00:12

B.M. Corwen


2 Answers

From what you describe, you seem to implement the Command pattern.

Command captures all information needed to perform certain action (not necessarily to undo this action). Your moves are basically commands.

Memento is a way to store state so that it is restoreable. Assume you'd have a class like GameState which represents the current state of the game. You'd be implementing Memento if your GameState would have methods like GameStateBackup createBackup() and restoreFromBackup(GameStateBackup).

Consider a game of chess where you'd want to be able to revert last x moves.

One way to do it would be to record all moves. You could then either "undo" moves. Or simple "replay" the first n-x moves. That would be the Command approach.

Another way would be to save the last x states of the game (and be able to restore them). This is the Memento approach.

You could actually use both patterns together. For instance, when implementation of "undo" would not be feasible you could record the state of the game before/after each move to make moves undoable.

like image 96
lexicore Avatar answered Dec 28 '22 08:12

lexicore


If you are undoing/redoing by executing commands on the state, that is the command pattern. If you are undoing/redoing by replacing state from a cache of states, that is the memento.

The difference between the Command and the Memento patterns for UNDO/REDO, is that in the Command pattern, you re-execute commands in the same order that changed attributes of a state, and with the Memento, you completely replace the state by retrieving from a cache/store. Design Patterns In Python: ASIN B08XLJ8Z2J

like image 27
Sean Bradley Avatar answered Dec 28 '22 07:12

Sean Bradley