Implementation

We will approach the implementation of Memento, in a simplified way, and by doing things in a natural way for the Python language. This means we do not necessarily need several classes.

One thing we will use is Python's pickle module. What is pickle used for? According to the module's documentation (https://docs.python.org/3/library/pickle.html), we can see that the pickle module can transform a complex object into a byte stream and it can transform the byte stream into an object with the same internal structure.

Let's take a Quote class, with the attributes text and author. To create the memento, we will use a method on that class, save_state(), which as the name suggests will dump the state of the object, using the pickle.dumps() ...

Get Mastering Python Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.