We tackle the memento pattern in this episode.  If you ever wanted to store the state of an object, then this is the one for you.  You can think of this pattern as a way to take note of your instance and store it for later.

The Memento Pattern Defined

As always, we will start with the “Gang of Four” intent to set the stage for our discussion.

“Without violating encapsulating, capture and externalize an object’s internal state so that the object can be restored to this state later.”

The trick to this intent is to avoid violating encapsulation.  The whole point of this pattern is to allow us to store and pass around the memento without having to keep track of the ways and places it is used.  Thus, proper encapsulation will enable us to keep the memento object self-contained outside of the knowledge it requires of the classes that use it.  Of course, that brings us to an essential part of this pattern.  It can sometimes be used to store the state and context of several types of objects.  Therefore, it does not have to be a one-to-one relationship.  Even the caretaker classes can be used to handle a large number of memento types when correctly designed.

Applying The Pattern

In most cases, you will want to start with an interface for the memento.  That will give you a signature that the caretaker object will use to handle the memento objects.  Then the memento itself is going to implement that interface.  You might even have a hierarchy of them to progressively store and transfer more details (properties) of the objects they work with.  Therefore, you will find access level restrictions along the lines of a friend or package level tend to work best.

Java, PHP, C#, etc.

This is one of the few patterns that can be implemented very differently depending on the language you are working with.  In particular, the languages that have a friend or helper concept built into them are going to have better-looking implementations.  This improvement is because implementing this pattern falls into that category of relationship.

Rob Broadhead

Rob is a founder of, and frequent contributor to, Develpreneur. This includes the Building Better Developers podcast. He is also a longtime student of technology as a developer, designer, and manager of software solutions. Rob is a founder and principle of RB Consulting and has managed to author a book about his family experiences. In his free time, he stays busy raising five children (although a few have grown into adults). When he has a chance to breathe, he is on the ice playing hockey to relax.

Leave a Reply