Denis' Micro Blog

Welcome! 👋

Design | Development | General
Guides | Life | Tips

A guide to the "Memento" pattern

April 10, 2023 | Development

Hey heeey...

hope you are doing well today. ♥️

Today I wanna show you something more "theoretical", a neat little design pattern called the "Memento" pattern.

Ever wondered how an "undo" function is done in a somewhat professional program? Well... This is how. (I mean... There are also some other measures we need to consider... But one step at a time. 😅)

If you want it a bit broader. Whenever you have an encapsulated object with an internal state and you want to expose/restore its state without breaking encapsulation. In this case, it's Memento time.

So, let's take a closer look.

As you can see, there are three parts to this pattern.

The first one is the actual encapsulated state object we want to expose. (Originator)

This exposed state is then represented in its object, the so-called Memento.

The last component describes the client (caretaker) who can request or pass back Mementos and uses that information.

The cool thing that, we can do now with this structure is the following. We can retrieve/create the state of the originator work with it safely and if the user decides to undo the operations by reinstating the original state Memento via a restoration function. All of that without violating the object's encapsulation, thus hiding implementation details during object interaction.

Cool isn't it? you probably find that only cool if you're way into this kind of stuff but yeah... 😅

If you wanna see some examples of how it's implemented, then check out the corresponding Wikipedia article, where there are a few ones in different programming languages.

I hope you found it also somewhat interesting. ❤

See ya