BehavioralC++verifiedVerified

Memento Pattern in C++

Captures and externalizes an object's internal state without violating encapsulation, allowing the object to be restored to that state later.

How to Implement the Memento Pattern in C++

1Step 1: Define the Memento (opaque snapshot)

class Memento {
    friend class TextEditor;
    std::string state_;
    explicit Memento(std::string state) : state_(std::move(state)) {}
};

2Step 2: Originator that creates and restores from mementos

class TextEditor {
    std::string text_;
public:
    void type(const std::string& s) { text_ += s; }

    Memento save() const { return Memento(text_); }
    void restore(const Memento& m) { text_ = m.state_; }

    const std::string& getText() const { return text_; }
};

3Step 3: Caretaker manages the memento history

class History {
    std::vector<Memento> snapshots_;
public:
    void push(Memento m) { snapshots_.push_back(std::move(m)); }

    Memento pop() {
        auto m = std::move(snapshots_.back());
        snapshots_.pop_back();
        return m;
    }

    bool empty() const { return snapshots_.empty(); }
};

int main() {
    TextEditor editor;
    History history;

    editor.type("Hello");
    history.push(editor.save());

    editor.type(" World");
    history.push(editor.save());

    editor.type("!!!");
    std::cout << "Current: " << editor.getText() << "\n";

    editor.restore(history.pop());
    std::cout << "Undo 1: " << editor.getText() << "\n";

    editor.restore(history.pop());
    std::cout << "Undo 2: " << editor.getText() << "\n";
}

Memento Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Memento Pattern in the Real World

Think of a video game save point. When you save, the game (originator) packages your character's stats, inventory, and position into a save file (memento). The save system (caretaker) stores these files without understanding their contents. When you die and reload, the save file is handed back to the game, which restores everything exactly as it was.