Memento Pattern


In this article I would like to experiment with the Memento pattern. Memento pattern provides an Object Oriented way of saving the state of an object.

The state called as Memento can be used to restore the object later.

The English meaning of Memento is Reminder of Past Events.

Challenge

You are working on a drawing application which allows the user to draw lines on a Canvas. The user should be able to save the state on particular intervals so any further mistakes could be undone. You need to provide a solution for the problem.

Definition

"Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later".

Implementation

The above problem can be solved using the Memento Pattern. This pattern, as stated in the definition, saves the internal state of the object for restoration later. The object state is saved without violating Encapsulation.

Momento1.gif

Following is the Drawing class definition:

Momento2.gif

  • The AddLine() method allows to add line on the graphics. These information are stored inside the _list object as state.
  • The CreateMemento() allows to get a copy of the internal state without violating Encapsulation.
  • The RestoreMemento() allows to restore the state to the given memento.

Following is the Memento class definition:

Momento3.gif

It contains the State property to hold the State of Drawing class.

Executing the Application

You can try executing the attached application. After executing draw a series of lines in the Canvas and use the Save button to save the memento.

Momento4.gif

Now try to add some unwanted lines:

Momento5.gif

Use the Restore State to get the old valid state.

Momento6.gif

So this concludes our application implementing Memento pattern.

Comparing Command and Memento Patterns

The Command pattern also provides the Undo / Redo functionality by converting actions to commands. The difference would be that the Command pattern stores each action but the Memento pattern saves the state only on request.

Additionally, the Command pattern has Undo and Redo operations for each action, but the Memento does not need that.

Depending on the scenario, Command / Memento pattern could be used.

Summary

In this article we have explore the Memento pattern. The attached source code contains the example we discussed.
 


Similar Articles