vxh.viet
8/30/2017 - 5:56 AM

Implementation of Command and Memento pattern to provide undo redo feature

Implementation of Command and Memento pattern to provide undo redo feature

Source: CodingInFlipflop, CodingInFlipflop, JournalDev, CodeProject, CodeProject

Question: How to implement undo redo feature?

Answer:

For detail of implementation see my Github.

Summary:

Command Pattern:

A combination of solution from CodingInFlipflops and CodeProject.

Use the idea of counter command: for each doIt() command, there's a counter undoIt() command that do exactly the opposite.

Use only one stack with pointer to manipulate undo and redo.

Pros:

  • Light on memory.

Cons:

  • Have to make Command type equal to the number of operations whether an operation is very small or big. As operations increase, commands increase.

  • Have to tranverse the stack to reach to desired state: For example to reach to state 3 of this stack:

current stack: operation +1

0 1 2 3 4 5 6 7 8

to reach to 3:

0 1 2 3 <-undoIt()- 4 <-undoIt()- 5 <-undoIt()- 6 <-undoIt()- 7 <-undoIt()- 8

Command Pattern:

A combination of solution from CodingInFlipflops and JournalDev.

Use a smiliar stack to hold the Memento.

Use a Caretaker to handle save and restore state.

Pros:

  • Performs well in change management.

  • Can switch to any state.

Cons:

  • Memory intensive.