-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.ts
70 lines (53 loc) · 1.58 KB
/
client.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
// The Strategy Pattern Example Use Case
class GameCharacter {
// This is the context whose strategy will change
#position: [number, number] = [0, 0];
move(movementStyle: IMoveConstructor) {
// The movement algorithm has been decided by the client
new movementStyle().move(this.#position);
}
}
interface IMoveConstructor {
// A Constructor for the IMove
new (): IMove;
}
interface IMove {
// The Move Strategy Interface
move(position: [number, number]): void;
}
class Walking implements IMove {
// A concrete movement strategy for walking
move(position: [number, number]) {
position[0] += 1;
console.log(`I am Walking. New position = ${position}`);
}
}
class Sprinting implements IMove {
// A concrete movement strategy for sprinting
move(position: [number, number]) {
position[0] += 2;
console.log(`I am Running. New position = ${position}`);
}
}
class Crawling implements IMove {
// A concrete movement strategy for crawling
move(position: [number, number]) {
position[0] += 0.5;
console.log(`I am Crawling. New position = ${position} `);
}
}
// The Client
const GAME_CHARACTER = new GameCharacter();
// If comment out the IMoveConstructor, well have to write it like this
// GAME_CHARACTER.move(new Walking());
GAME_CHARACTER.move(Walking);
// Character sees the enemy
GAME_CHARACTER.move(Sprinting);
// Character finds a small cave to hide in
GAME_CHARACTER.move(Crawling);
/* OUTPUT
~ node ./dist/behavioural/strategy/client.js
I am Walking. New position = 1,0
I am Running. New position = 3,0
I am Crawling. New position = 3.5,0
*/