Skip to main content

Command Palette

Search for a command to run...

Memento Design Pattern in Python...

Updated
2 min readView as Markdown
S
In search of WhoAmI...

title: Memento Design Pattern in Python... date: '2000-01-01' tags:

  • Uncategorized

This design pattern lets you save the state of an object without revealing the implementation.

There are mainly three participants in this design pattern

- Memento: stores the internal state of the Originator object. How much state of the Originator the memento will store completely depends upon the Originator

- Originator: It creates a memento containing a snapshot of its current internal state. It also uses the Memento to restore the Original state

Caretaker: It's responsible for the memento's safekeeping.

The memento design pattern helps to implement Undo facilities for any application. Think about a word processor app - at any point in time we can undo and get back the earlier state of the document - here lies the greatness of the memento design pattern.

The UML class diagram of the Memento pattern looks like the following:

The source code for the Memento Design Pattern is as follows:

Here's the formatted version of your code:

class Originator:
    _state = ""

    def set(self, state):
        print(f"Originator: Setting state to {state}")
        self._state = state

    def save_to_memento(self):
        return Memento(self._state)

    def restore_from_memento(self, m):
        self._state = m.get_saved_state()
        print(f"Originator: State after restoring from Memento: {self._state}")


class Memento:
    def __init__(self, state):
        self._state = state

    def get_saved_state(self):
        return self._state


class Caretaker:
    def __init__(self, originator):
        self.originator = originator
        self.saved_states = []

    def saveState(self):
        self.saved_states.append(self.originator.save_to_memento())

    def undo(self):
        if not len(self.saved_states):
            return
        self.originator.restore_from_memento(self.saved_states.pop())


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    originator = Originator()
    caretaker = Caretaker(originator)

    originator.set("State1")
    caretaker.saveState()

    originator.set("State2")
    caretaker.saveState()

    originator.set("State3")
    caretaker.saveState()

    originator.set("State4")
    caretaker.saveState()

    print("\nClient: Now, let's rollback!\n")
    caretaker.undo()

    print("\nClient: Once more!\n")
    caretaker.undo()

This version includes proper indentation and formatting for better readability.

If we run the above lines of code, the output will be:

Originator: Setting state to State1

Originator: Setting state to State2

Originator: Setting state to State3

Originator: Setting state to State4

Client: Now, let's rollback!

Originator: State after restoring from Memento: State4

Client: Once more!

Originator: State after restoring from Memento: State3

More from this blog

Som's Tech World...

150 posts

I am in search of WhoAmI. This is my own world of technologies and software. I believe in the following simple fact of life... To win is no more than this... To rise each time you fall...