terminal

codeando_simple

terminal

menu

terminal

search_module

guest@codeandosimple: ~/system/search $ grep -r "" .

Press [ENTER] to execute search

Status

Engine: Ready

Database: Online

Index: V2.1.0_LATEST

bash -- cat memento.md
guest@codeandosimple: ~/blog/design-patterns $ cat memento.md

Memento Pattern_

// "Don't let what you cannot do interfere with what you can do" - John Wooden

# Purpose

Captures and stores the current state of an object to be able to restore it later, without violating encapsulation.

# Problem

  • State Restoration: Need to go back without exposing internal implementation.

  • Encapsulation Violation: Prevent external objects from manipulating the private state.

# Solution

Delegate the creation of a state copy (Memento) to the object itself (Originator). A Caretaker manages the history without seeing the details.

# Structure

Memento UML Structure

# Participants

  • Memento: The state snapshot.
  • Originator: Creates the memento and restores its state from it.
  • Caretaker: Maintains the memento stack (history).

# When to Use It

To implement "undo/redo" functionality or naturally keep state histories without exposing the origin class.

# Advantages

  • verified

    Encapsulation: The state remains private.

  • verified

    Simplification: Originator doesn't manage its own history.

# Disadvantages

  • warning

    Memory: Many snapshots consume significant resources.

  • warning

    Incompatibility: Old mementos can fail if the class changes.

# Example: Text Editor (Undo)

Store editor content before each change in a stack to allow rollback.

Memento Editor Example

# Java Code

class Memento {
    private final String state;
    public Memento(String s) { state = s; }
    public String getState() { return state; }
}

class Editor {
    private String text;
    public Memento save() { return new Memento(text); }
    public void undo(Memento m) { text = m.getState(); }
}

# Mapping Participants

  • TextMemento: Memento.
  • TextEditor: Originator.
  • Caretaker: Change stack manager.

# Conclusions

Robust solution to implement state rollback in a clean and maintainable way.

# Related Patterns

Command

To implement complete reversible actions.

Iterator

To navigate the memento history.