Skip to content

Conversation

@ilopX
Copy link
Collaborator

@ilopX ilopX commented Jan 27, 2022

Memento pattern

Memento is a behavioral design pattern that lets you save and restore the previous state of an
object without revealing the details of its implementation.

Tutorial: here.

Conceptual Editor example

This example uses the Memento pattern alongside the Command pattern for storing snapshots of the
complex text editor’s state and restoring an earlier state from these snapshots when needed.

More detailed explanation on RefactoringGuru.

Diagram:

image

Client code:

void main() {
  final editor = Editor('New Document');
  final firstState = Command.makeBackup(editor);
  editor.text += ' add text';
  final secondState = Command.makeBackup(editor);

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

  firstState.undo();
  print('First state: "${editor.text}"');

  secondState.undo();
  print('Second state: "${editor.text}"');
}

Output:

Current state: "New Document add text"
First state: "New Document"
Second state: "New Document add text"

@neochief neochief merged commit 3a98693 into RefactoringGuru:master Jan 27, 2022
@ilopX ilopX deleted the add-official-example-memento-pattern branch January 27, 2022 12:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants