-
-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathclient.ts
More file actions
83 lines (72 loc) · 1.98 KB
/
Copy pathclient.ts
File metadata and controls
83 lines (72 loc) · 1.98 KB
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
// The State Use Case Example
enum ExampleState {
Initializing = 'Initializing',
Started = 'Started',
Running = 'Running',
Finished = 'Finished',
}
interface IExampleState {
// A State Interface
request(): void
}
class StateContext implements IExampleState {
#state: ExampleState
constructor() {
this.#state = ExampleState.Initializing
}
public get state() {
return this.#state
}
public set state(value: ExampleState) {
switch (value) {
case ExampleState.Started:
this.request = Started.prototype.request
break
case ExampleState.Running:
this.request = Running.prototype.request
break
case ExampleState.Finished:
this.request = Finished.prototype.request
break
}
this.#state = value
}
request() {
// Does nothing until state changes, when then
// this method handle is reassigned to a different
// concrete states request method
}
}
class Started implements IExampleState {
// A ConcreteState Subclass
request() {
console.log(`I am now Started`)
}
}
class Running implements IExampleState {
// A ConcreteState Subclass
request() {
console.log(`I am now Running`)
}
}
class Finished implements IExampleState {
// A ConcreteState Subclass
request() {
console.log(`I am now Finished`)
}
}
// The Client
const STATE_CONTEXT = new StateContext()
console.log('STATE_CONTEXT = ' + STATE_CONTEXT.state)
STATE_CONTEXT.state = ExampleState.Started
STATE_CONTEXT.request()
STATE_CONTEXT.state = ExampleState.Running
STATE_CONTEXT.request()
STATE_CONTEXT.state = ExampleState.Finished
STATE_CONTEXT.request()
STATE_CONTEXT.state = ExampleState.Started
STATE_CONTEXT.request()
STATE_CONTEXT.state = ExampleState.Running
STATE_CONTEXT.request()
STATE_CONTEXT.state = ExampleState.Finished
STATE_CONTEXT.request()