This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Design Patterns
.NET 1.1+

Memento Design Pattern

The memento pattern is a design pattern that permits the current state of an object to be stored without breaking the rules of encapsulation. The originating object can be modified as required but can be restored to the saved state at any time.

Testing the Memento

To test the memento we can use a console application to instantiate the various objects and monitor the results. In the following code several modifications to a Book object are made and details of the book's state are outputted to the console. In the first stage, the book is initialised. The thread is then paused for two seconds so that it is easy to see the changes to the last updated time.

In the second stage, a Memento for the book is created and stored in a Caretaker object. The book is then edited and the new details outputted to the console. Finally, the book is restored to its earlier state using the RestoreFromUndo method. This resets the book's state using the contents of the Memento from within the Caretaker.

// Initialise book
Book book = new Book();
book.ISBN = "0450488357";
book.Title = "The Tommyknockers";
book.Author = "Stephen King";

// Set undo point
Caretaker history = new Caretaker();
history.Memento = book.CreateUndo();

// Modify book
book.ISBN = "0330376144";
book.Title = "The Rats";
book.Author = "James Herbert";

// Undo

/* OUTPUT - Will vary according to local date and time settings

0450488357 - 'The Tommyknockers' by Stephen King, edited 18/07/2009 15:01:24.
0330376144 - 'The Rats' by James Herbert, edited 18/07/2009 15:01:26.
0450488357 - 'The Tommyknockers' by Stephen King, edited 18/07/2009 15:01:24.

18 July 2009