Bird
Raised Fist0

Consider this simplified Python code using the Memento pattern:

medium📝 Analysis Q13 of Q15
LLD - Behavioral Design Patterns — Part 2
Consider this simplified Python code using the Memento pattern:
class Memento:
    def __init__(self, state):
        self._state = state

class Originator:
    def __init__(self):
        self._state = ""
    def set_state(self, state):
        self._state = state
    def save(self):
        return Memento(self._state)
    def restore(self, memento):
        self._state = memento._state

originator = Originator()
originator.set_state("State1")
memento = originator.save()
originator.set_state("State2")
originator.restore(memento)
print(originator._state)

What will be printed?
ANone
BState2
CState1
DError
Step-by-Step Solution
Solution:
  1. Step 1: Trace state changes in Originator

    Initially, Originator's state is set to "State1". Then a Memento is saved capturing "State1". Next, state changes to "State2".
  2. Step 2: Restore state from Memento

    Calling restore with the saved Memento sets the state back to "State1". The print statement outputs the restored state.
  3. Final Answer:

    State1 -> Option C
  4. Quick Check:

    Restore resets state to saved value [OK]
Quick Trick: Restore sets state back to saved snapshot [OK]
Common Mistakes:
MISTAKES
  • Assuming print shows latest state before restore
  • Confusing save and restore methods
  • Expecting error due to private variable access

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes