-
Notifications
You must be signed in to change notification settings - Fork 2
/
Momento.ts
107 lines (85 loc) · 2.03 KB
/
Momento.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
class State {
private _value: String;
constructor(value: string) {
this._value = value;
}
public set value(newValue: String) {
this._value = newValue;
}
public get value() {
return this._value;
}
}
interface StateInterface {
state: State;
}
class Memento implements StateInterface {
private _state: State;
constructor(state: State) {
this._state = state;
}
public set state(newState: State) {
this._state = newState;
}
public get state() {
return this._state;
}
}
class Originator implements StateInterface {
private _state: State;
constructor(state: State) {
console.log(state.value);
this._state = state;
}
public set state(state: State) {
console.log(state.value);
this._state = state;
}
public get state() {
return this._state;
}
public createMemento() {
console.log(`create ${this._state.value} memento`);
return new Memento(this._state);
}
public restoreMemento(memento: Memento) {
console.log(`restore ${memento.state.value}`);
this._state = memento.state;
}
}
class CareTaker {
private _memento: Memento;
constructor() {
this._memento = new Memento(new State("Initial State"));
}
public set memento(memento: Memento) {
// memento saved
this._memento = memento;
}
public get memento() {
return this._memento;
}
}
// USAGE:
// Save check point
const oldState = new State('check point');
const originator = new Originator(oldState);
const careTaker = new CareTaker();
careTaker.memento = originator.createMemento();
// Player dies
const currentState = new State('die');
originator.state = currentState;
// Player reset to check point
originator.restoreMemento(careTaker.memento);
// Player gain medel
const medalState = new State('get medal');
originator.state = medalState;
// Save
careTaker.memento = originator.createMemento();
// OUTPUT:
// "check point"
// "create check point memento"
// "die"
// "restore check point"
// "get medal"
// "create get medal memento"