design-patterns

Quick-reference guide to software design patterns with concise Dart examples.

View project on GitHub

Captures and restores an object’s internal state without violating encapsulation.

Think undo/redo or save points.

class Memento {
  final String _state;
  Memento(this._state);
}

class Editor {
  String content = '';

  Memento save() => Memento(content);
  void restore(Memento m) => content = m._state;
}

class History {
  final List<Memento> _snapshots = [];

  void push(Memento m) => _snapshots.add(m);
  Memento pop() => _snapshots.removeLast();
}

// Usage
final editor = Editor();
final history = History();

editor.content = 'Hello';
history.push(editor.save());

editor.content = 'Hello World';
history.push(editor.save());

editor.content = 'Oops';
editor.restore(history.pop()); // back to "Hello World"
print(editor.content);