-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy.ts
More file actions
87 lines (78 loc) · 2.4 KB
/
strategy.ts
File metadata and controls
87 lines (78 loc) · 2.4 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
84
85
86
87
/*
* strategy.ts
* Turning behavioural control interfaces into a Strategy Pattern
* Strategy – swap algorithms at runtime
* We can compose controls in a modular, extensible way
* Strategy defines a family of behaviours, encapsulates each one, and makes them interchangeable.
* Plug-and-play control modules — the device doesn't care how something works,
* just that it has the correct control plugged in.
* This allows us to change the behaviour of a device at runtime
* without modifying the device's code.
* This example shows how to implement a strategy pattern as a universal remote control.
*/
import { PowerControl, VolumeControl, ChannelControl } from "../interface";
export class DefaultPower implements PowerControl {
powerOn(): void {
console.log("Powering on.");
}
powerOff(): void {
console.log("Powering off.");
}
}
export class LoudVolume implements VolumeControl {
volumeUp(): void {
console.log("Volume cranked up.");
}
volumeDown(): void {
console.log("Volume dropped down.");
}
mute(): void {
console.log("Muted");
}
unmute(): void {
console.log("Unmuted");
}
}
export class BasicChannelControl implements ChannelControl {
private currentChannel = 1;
channelUp(): void {
this.currentChannel++;
console.log(`Next Channel: ${this.currentChannel}`);
}
channelDown(): void {
this.currentChannel--;
console.log(`Previous Channel: ${this.currentChannel}`);
}
changeChannelTo(channel: number): void {
this.currentChannel = channel;
console.log(`Changing to ${channel}`);
}
}
export class SilentVolume implements VolumeControl {
private volume = 0;
volumeUp(): void {
console.log("Volume is locked to silent");
}
volumeDown(): void {
console.log("Volume is already silent");
}
mute(): void {
console.log("Muted (already silent)");
}
unmute(): void {
console.log("Unmute not allowed - silent mode active.");
}
}
export class FancyChannelGuide implements ChannelControl {
private currentChannel = 100;
channelUp(): void {
console.log("Navigate Up");
}
channelDown(): void {
console.log("Navigate Down");
}
changeChannelTo(channel: number): void {
this.currentChannel = channel;
console.log(`Changing to ${channel}`);
}
}