-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathState.ts
89 lines (72 loc) · 2.15 KB
/
State.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
interface ATMState {
name?: string;
takeCash(cash: number): void;
}
class ATMHasCashState implements ATMState {
private _machine: ATMMachine;
name: string;
constructor(machine: ATMMachine, name: string) {
this.name = name;
this._machine = machine;
}
takeCash(cash: number): void {
if (this._machine.cash < cash) {
this._machine.state = this._machine.noCashState();
console.log('Not enough cash');
return;
} else if (this._machine.cash === cash) {
this._machine.state = this._machine.noCashState();
console.log('No cash after cash token');
}
console.log(`${this._machine.cash} - ${cash}`);
this._machine.cash -= cash;
}
}
class ATMNoCashState implements ATMState {
private _machine: ATMMachine;
name: string;
constructor(machine: ATMMachine, name: string) {
this.name = name;
this._machine = machine;
}
takeCash(cash: number): void {
throw new Error('ATMMachine has no cash');
}
}
class ATMMachine implements ATMState {
private _hasCashState: ATMHasCashState;
private _noCashState: ATMNoCashState;
private _currentState: ATMState;
public cash: number;
constructor(cash: number) {
this.cash = cash;
this._hasCashState = new ATMHasCashState(this, 'HasCash');
this._noCashState = new ATMNoCashState(this, 'NoCash');
this._currentState = this.cash ? this._hasCashState : this._noCashState;
}
public set state(value: ATMState) {
console.log(`Current state is ${value.name}`);
this._currentState = value;
}
public get state() {
return this._currentState;
}
takeCash(cash: number): void {
this._currentState.takeCash(cash);
}
// Get states
public hasCashState() {
return this._hasCashState;
}
public noCashState() {
return this._noCashState;
}
}
// USAGE:
const machine = new ATMMachine(1000);
machine.takeCash(200); // has cash
machine.takeCash(1000); // not enough
// OUTPUT:
// "1000 - 200"
// "Current state is NoCash"
// "Not enough cash"