Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 57 ยท Behavioral Patterns

Mediator and Memento

Learn the Mediator pattern to centralize communication between objects and the Memento pattern to save and restore state for undo, with runnable examples.

Two behavioral patterns solve two very different headaches. Mediator fixes the tangle that appears when many objects talk directly to many other objects: it puts one object in the middle, and everybody talks only to that object. Memento fixes the problem of saving an object's state so you can put it back later, without letting outsiders poke around in the object's private fields.

They share a lesson: both move something awkward (who talks to whom, who knows how the state looks inside) into a single, well-defined place. We will take them one at a time and finish with a short comparison.

Mediator in one picture

Without it Every object knows every other object.
With it Objects only know the mediator.
Easy change Rules live in one class, not in ten.

N objects talking to each other need up to N x (N - 1) links. With a mediator you need N.

1 / 2

Mediator: one object in the middle

Picture a chat room. If every user held a list of every other user and sent messages to each one directly, adding a user would mean updating everybody. Banning a user, muting, private messages and "do not disturb" rules would all have to be repeated in every user class.

With the Mediator pattern the users (called colleagues) know only the chat room. A user says "send this message" to the room; the room decides who should receive it and delivers it. The colleagues are decoupled from each other, and the coordination rules sit in one place.

flowchart LR
    A["User Ana"] --> R["ChatRoom<br/>(mediator)"]
    B["User Bo"] --> R
    C["User Cy"] --> R
    R --> A
    R --> B
    R --> C

Every user talks only to the room. The room decides who receives each message.

JS A chat room mediator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

User has no idea how many other users exist, and it contains no filtering logic. The mute rule was added in the room only; no user class changed. That is the benefit: new rules (rate limits, banned words, message history) go into the mediator.

Where the mediator shows up in real code

  • GUI dialogs. A form where ticking a box enables a text field and disables a button is classic mediator territory. Instead of each widget updating the others, a dialog controller reacts to events and updates the widgets.
  • Air traffic control. Planes do not talk to each other; they talk to the tower.
  • Message buses and event hubs. A central bus delivers events between components, as in Observer, though an observer's subject broadcasts to anyone who subscribed, while a mediator applies coordination rules that may be specific to each pair.
  • MediatR-style libraries in .NET, which route a request object to its handler.

The main risk

The mediator can turn into a "god object" that knows too much. All the complexity you removed from the colleagues now lives in one class. Keep the mediator focused on coordination, split it by feature when it grows (one mediator per dialog or per room type), and push business rules back into domain objects. See Anti-Patterns and Code Smells for the god object smell.

Memento: saving state without breaking encapsulation

You want an "undo" or a "save game". The simplest idea is to copy the object's fields from the outside, but that forces the object to expose all its private state, and everyone who copies it becomes coupled to its internals.

The Memento pattern has three roles:

  • the originator is the object whose state you want to save. It creates a memento holding a snapshot, and can restore itself from one;
  • the memento is an opaque value object holding the saved state. Only the originator needs to read it;
  • the caretaker keeps mementos (for example, in a stack) and hands them back, but never looks inside.
JS A text editor with snapshots

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Here the editor's text and cursor are private (#text, #cursor). The history stores snapshots but cannot read or alter them; the snapshot is frozen. In Java you would get the same effect with a private nested class for the memento, and in C++ with a friend declaration so that only the originator can reach the memento's data.

Snapshots versus commands

Undo can be built two ways. With Memento you store the whole state (or a diff of it) and restore it. With Command you store the operation together with how to reverse it. The trade-off:

Memento Command with undo
Stores Copies of state Operations and their inverses
Memory Grows with state size Small per step
Undo logic Trivial: put the state back You must write a correct inverse for each command
Good for Small state, "save game", transactions Large documents, fine-grained edits

Many real editors combine them: commands for normal editing, and a memento taken at checkpoints.

Costs to watch for

  • Memory. Saving the full state after every keystroke of a large document is expensive. Store only changes (a delta), cap the history, or use structural sharing with immutable data.
  • Shallow copies. If the state contains nested objects, copy them deeply when taking a snapshot. Otherwise the snapshot changes when the live object does. Compare Prototype for deep versus shallow copying.
  • Resources. Snapshots cannot capture things like open files or network connections; restore only data.

Mediator or Memento, or neither?

Use Mediator when you see a web of objects that all reference each other, or when changing one component forces edits in many others. Use Memento when you need undo, rollback, checkpoints or "save and resume" and the originator must keep its internals private. If you only have two objects, a direct reference is simpler. If state is already an immutable value, "saving" it is just keeping a reference, and no pattern is needed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What problem does the Mediator pattern address?

    A mediator becomes the single point of communication, so colleagues depend on it instead of on each other.
  2. 2. In the chat room example, where does the mute rule live?

    The room applies routing rules, so adding the rule required no change to the User class.
  3. 3. What is the caretaker's job in the Memento pattern?

    The caretaker only keeps mementos (for example in a stack). The originator is the only class that creates and reads them.
  4. 4. What is a typical risk of a Mediator?

    All coordination logic moves into one class, so you should keep it focused and split it by feature as it grows.
  5. 5. Why must a snapshot of an object with nested mutable data usually be a deep copy?

    A shallow copy shares nested objects with the original, so later edits would silently alter the saved state.

Summary

  • Mediator centralizes communication: colleagues know the mediator, not each other.
  • Routing and coordination rules live in the mediator; beware of it becoming a god object.
  • Memento captures state in an opaque snapshot so the originator can restore itself without exposing internals.
  • Roles: originator creates and restores, memento holds data, caretaker stores mementos.
  • Memento stores state; Command stores operations. Real editors often combine both.
  • Watch memory use and use deep copies when snapshots include nested data.

Next lesson: Visitor, Interpreter and Null Object.