What Is This Pattern?

The Memento pattern seeks to capture and externalize and object's state so that the object can be restored to this state at a later time.

The purpose of this pattern is to separate the current state of the object from a previous state, so that if something happens to the current state (it gets corrupted, it gets lost, it tries to secede from the Union) the object's state can be restored from its Memento (whether via a civil war or other, less interesting methods).

The Rundown

The Participants

The Memento stores internal state of the Originator object. The Memento has no limit on what it may or may not store (e.g. as much or as little of the Originator's state as needed).

The Originator creates a Memento containing a "snapshot" of its internal state, and then later uses that memento to restore its internal state.

The Caretaker is responsible for the Memento's safekeeping, but does not operate on or examine the contents of that Memento.

A Delicious Example

Well, in so far as "delicious" means "fitting the food theme" but anyway.

Let's imagine a system in which a restaurant needs to record information about the suppliers that bring them their ingredients. For example, a really high-end restaurant might order directly from a local farm, and the restaurant needs to keep track of which ingredients come from which suppliers.

In our system, we need to keep track of how much information we enter about a particular supplier, and be able to restore that information to a previous state if we, say, accidentally enter the wrong address. We can demo this using the Memento pattern.

First, let's create our Originator participant, which will create and use Mementos:

Will I Ever Use This Pattern?

Maybe? I'm really not sure.. I struggled for a long time to come with appropriate scenarios for this that couldn't be covered by other architectures, and eventually gave up as I simply couldn't think of one. That said, I'm happy to be wrong, so if anyone would like to give real-world examples using the Memento pattern, please feel free to share in the comments!

Summary

The Memento design pattern seeks to encapsulate state of an object as another object (called a Memento) and enable the ability to restore the state of the object from that Memento.

As always, I like to provide code with my tutorials, so the repository for this pattern is over on GitHub and contains all of the sample code used here.