Iterator, Mediator, and Memento Patterns (GoF Behavioral Patterns)

This page covers the tail end of the Iterator pattern (internal iterators, known uses, and related patterns), the complete Mediator pattern, and most of the Memento pattern. These are behavioral patterns from the Gang of Four catalog concerned with managing object communication, state capture, and traversal.

Key Concepts

Iterator (conclusion)

Mediator

Memento

Commands and Syntax

Mediator — FontDialogDirector example (C++)


class DialogDirector {
public:
    virtual void ShowDialog();
    virtual void WidgetChanged(Widget*) = 0;
protected:
    virtual void CreateWidgets() = 0;
};

class Widget {
public:
    Widget(DialogDirector*);
    virtual void Changed();  // calls _director->WidgetChanged(this)
private:
    DialogDirector* _director;
};

Memento — C++ friend idiom for dual interfaces


class Memento {
public:
    virtual ~Memento();          // narrow public interface
private:
    friend class Originator;     // wide interface via friend
    Memento();
    void SetState(State*);
    State* GetState();
};

Memento — Command integration for undo


void MoveCommand::Execute() {
    _state = solver->CreateMemento();  // checkpoint before action
    _target->Move(_delta);
    solver->Solve();
}
void MoveCommand::Unexecute() {
    _target->Move(-_delta);
    solver->SetMemento(_state);        // restore previous state
    solver->Solve();
}

Relationships

Exam-Relevant Points