The Memento pattern provides you with the ability to restore an object to its previous state (undo by rollback).

image

The Memento pattern can have different purposes, but above all is known as the Undo Pattern. If you are mentally in an object oriented mood you could ask yourself…

Why on earth and above want they to put the internal data outside of the class in question? That’s not data hiding, is it?

… but the truth is that memento pattern doesn’t violate encapsulation of the internal state.

As a consequence, this pattern can come very handy when you want to store its internal state and reclaim it later without knowledge of the original object.

The client creates an originator object, which has a certain internal state. This can be any object, of course. The important objects are the caretaker and memento. A memento is created by the originator and stored in the caretaker. At a later point in time the previous state can be restored by setting the originators memento to the caretaker’s stored memento.

The originator object can be any object, as long as they implement a CreateMemento and SetMemento method. The CreateMemento method should return a filled memento object, whilst the SetMemento should read the data stored in the memento and restore its internal state.

The Memento object contains the originators internal state, so must have a similar structure. To design a Memento class you could start with a copy of the originator class and strip all unnecessary methods and attributes.

The Caretaker only contains the memento. In this example there is just one memento, but normally the caretaker contains a list of mementos.

And of course, you can click here for a simplified

This post is part of my series on the foundational design patterns in C#. In this series I explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.