Today, I will show you how to implements the Memento design pattern in Python. Assuming, that you are in a position where you want to implement an undo system. So you have an object where you should keep all the changes that user made on it.
How it works?
If you take a look to Memento pattern in Wikipedia, you’ll find this:
The memento pattern is implemented with three objects: the originator, a caretaker and a memento. The originator is some object that has an internal state. The caretaker is going to do something to the originator, but wants to be able to undo the change. The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do. To roll back to the state before the operations, it returns the memento object to the originator. The memento object itself is an opaque object (one which the caretaker cannot, or should not, change). When using this pattern, care should be taken if the originator may change other objects or resources – the memento pattern operates on a single object.
Let’s now, rewrite the Java example from the wiki in Python:
I don’t like this implementation, there are many lacks on it, especially if you are Pythonista:
- We have not a general purpose for the Originator class
- We should manage what attributes to save on the Memento
- We should create a CakeTaker explicitly for every object
As an enhancement to this implementation, I want :
- to create a CakeTake object implicitly for each Originator class
- that the CakeTaker create a Memento object for every change in the Originator behind the scene
- possibility to have a Memento for a group of changes
Ok, next time I will implement this enhancement and will discuss the solution, nice day.