Skip to content

Commit 852550b

Browse files
committed
Add memento pattern example for solution
1 parent e48302c commit 852550b

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

src/Memento/Book/index.ts

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
export interface Memento {
2+
getName(): string;
3+
getSnapshotDate(): Date;
4+
getText(): string;
5+
}
6+
7+
class Editor {
8+
private text: string;
9+
10+
constructor(private name: string) {
11+
this.text = "";
12+
}
13+
14+
makeSnapshot(): Memento {
15+
return new Snapshot(this.name, this.text);
16+
}
17+
18+
restore(memento: Memento) {
19+
this.text = memento.getText();
20+
}
21+
22+
editText(newText: string) {
23+
this.text = newText;
24+
}
25+
26+
displayText() {
27+
console.log("Current Text: " + this.text);
28+
}
29+
}
30+
31+
class Snapshot implements Memento {
32+
private name: string;
33+
private text: string;
34+
private date: Date;
35+
36+
constructor(name: string, text: string) {
37+
this.name = name;
38+
this.text = text;
39+
this.date = new Date();
40+
}
41+
42+
getName(): string {
43+
return this.name;
44+
}
45+
46+
getSnapshotDate(): Date {
47+
return this.date;
48+
}
49+
50+
getText(): string {
51+
return this.text;
52+
}
53+
}
54+
55+
const editor = new Editor("Document 1");
56+
57+
editor.editText("This is the initial text");
58+
editor.displayText();
59+
60+
const snapshot1 = editor.makeSnapshot();
61+
62+
editor.editText("Text after editing");
63+
editor.displayText();
64+
65+
editor.restore(snapshot1);
66+
editor.displayText();

0 commit comments

Comments
 (0)