Thursday, August 24, 2023

Memento Design Pattern in Python...

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:

cclass Originator:
    _state = ""

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

def save_to_memento(self):
return self.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()

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

No comments: