Skip to content

Commit 0b54d26

Browse files
committed
Add README to "Memento" conceptual example.
1 parent d36abb8 commit 0b54d26

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Memento pattern
2+
Memento is a behavioral design pattern that lets you save and restore the previous state of an
3+
object without revealing the details of its implementation.
4+
5+
Tutorial: [here](https://refactoring.guru/design-patterns/memento).
6+
7+
## Conceptual Editor example
8+
This example uses the Memento pattern alongside the Command pattern for storing snapshots of the
9+
complex text editor’s state and restoring an earlier state from these snapshots when needed.
10+
11+
More detailed explanation on [RefactoringGuru](https://refactoring.guru/design-patterns/memento?#pseudocode).
12+
13+
### Diagram:
14+
![image](https://user-images.githubusercontent.com/8049534/151352367-c97db094-fc87-4eb2-9210-581914c57ced.png)
15+
16+
### Client code:
17+
```dart
18+
void main() {
19+
final editor = Editor('New Document');
20+
final firstState = Command.makeBackup(editor);
21+
editor.text += ' add text';
22+
final secondState = Command.makeBackup(editor);
23+
24+
print('Current state: "${editor.text}"');
25+
26+
firstState.undo();
27+
print('First state: "${editor.text}"');
28+
29+
secondState.undo();
30+
print('Second state: "${editor.text}"');
31+
}
32+
```
33+
34+
**Output:**
35+
```
36+
Current state: "New Document add text"
37+
First state: "New Document"
38+
Second state: "New Document add text"
39+
```

0 commit comments

Comments
 (0)