Memento#

The Memento design pattern is a behavioral design pattern that allows an object to save its state so that it can be restored later. This is useful for implementing features like undo/redo operations.

Imagine you have an object that you want to save the state of at a certain point in time. You can create a Memento object that stores the state of the object. Later, you can restore the object to that state using the Memento.

Common use cases#

  • Undo/Redo Mechanisms:
    • Applications like text editors, drawing applications, and IDEs often implement undo and redo functionality using the Memento pattern. Each change in the application’s state is saved as a Memento, allowing users to revert to previous states.

  • State Persistence:
    • Games often use the Memento pattern to save the state of a game at certain checkpoints. This allows players to resume the game from a saved state.

  • Transactional Systems:
    • In database systems or other transactional systems, the Memento pattern can be used to save the state before a transaction. If the transaction fails, the system can revert to the previous state.

  • Configuration Management:
    • Software that allows users to change settings or configurations can use the Memento pattern to save the current configuration. Users can then revert to a previous configuration if needed.

  • State History Tracking:
    • Applications that need to keep a history of states, such as version control systems, can use the Memento pattern to store snapshots of the state at different points in time.

  • Prototype-based Object Creation:
    • In scenarios where objects are created based on a prototype, the Memento pattern can be used to save the state of the prototype object, allowing new objects to be created with the same state.

These use cases leverage the Memento pattern’s ability to capture and restore an object’s state without violating encapsulation.

Key Components#

  • Originator: The object whose state needs to be saved and restored.

  • Memento: The object that stores the state of the Originator.

  • Caretaker: The object that keeps track of multiple Mementos. It does not modify or inspect the contents of the Memento.

--- Python Example ---
--- Java Example ---

In these examples, the Originator can save its state to a Memento and restore it later. The Caretaker manages the saved states without modifying them.