Design Pattern in Dart: Memento Pattern

What is the Memento Pattern?

The Memento Pattern is a behavioral design pattern that allows an object to:

Save and restore its state without exposing its internal implementation.

It’s like pressing “Ctrl+Z” or “Undo” — capturing a snapshot of the system’s state and rolling back when needed.


Use Cases

  • Undo/Redo functionality in text editors or drawing apps.
  • Snapshots of game states.
  • State restoration in mobile apps (e.g., draft restore).
  • Saving/rolling back configurations.

Key Concepts

RoleResponsibility
OriginatorThe object whose state needs to be saved/restored.
MementoStores the internal state of the Originator.
CaretakerManages the memento (e.g., history stack).

Dart Example: Text Editor Undo

We’ll implement a text editor with the ability to undo text changes.


Step 1: Memento (Snapshot of State)

class TextMemento {
final String text;

TextMemento(this.text);
}

Step 2: Originator (Editor)

class TextEditor {
String _text = "";

void type(String newText) {
_text += newText;
}

String get text => _text;

TextMemento save() {
return TextMemento(_text);
}

void restore(TextMemento memento) {
_text = memento.text;
}
}

Step 3: Caretaker (Undo Manager)

class TextHistory {
final List<TextMemento> _history = [];

void save(TextEditor editor) {
_history.add(editor.save());
}

void undo(TextEditor editor) {
if (_history.isNotEmpty) {
final last = _history.removeLast();
editor.restore(last);
}
}
}

Step 4: Client Code

void main() {
final editor = TextEditor();
final history = TextHistory();

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

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

editor.type("!!!");

print("Current Text: ${editor.text}");

history.undo(editor);
print("After Undo 1: ${editor.text}");

history.undo(editor);
print("After Undo 2: ${editor.text}");
}

Output

Current Text: Hello World!!!
After Undo 1: Hello World
After Undo 2: Hello

Why Use Memento in Dart?

Dart supports class encapsulation, making it easy to hide internal state logic while still providing a snapshot mechanism.

Memento is especially useful in Flutter apps where you:

  • Want draft saving for forms.
  • Provide step-by-step navigation with state rollback.
  • Offer Undo in canvas/drawing apps.

Summary

RoleClassDescription
OriginatorTextEditorHolds the state
MementoTextMementoStores a snapshot of state
CaretakerTextHistoryManages undo/redo history

Gotchas

  • If mementos are too large, it can consume memory quickly.
  • Memento pattern works best with immutable snapshots.
  • You may need deep copies to avoid mutating shared references.

Use Cases in Flutter

  • State restoration with RestorationMixin.
  • Undo stack for canvas using CustomPainter.
  • Managing form field values over time.

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Lên đầu trang