-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrategy.ts
More file actions
39 lines (31 loc) · 953 Bytes
/
Copy pathStrategy.ts
File metadata and controls
39 lines (31 loc) · 953 Bytes
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
interface Strategy {
doWork(data: string[]): string[];
}
class Context {
private currentStrategy: Strategy;
constructor(strategy: Strategy) {
this.currentStrategy = strategy;
}
setStrategy(strategy: Strategy): void {
this.currentStrategy = strategy;
}
doStrategyWork(): void {
console.log('Context: Sorting data using some strategy.');
const result = this.currentStrategy.doWork(['a', 'b', 'c', 'e', 'd']);
console.log('Context: Result: ' + result.join(','));
}
}
class AscendingStrategy implements Strategy {
doWork(data: string[]): string[] {
return data.sort();
}
}
class DescendingStrategy implements Strategy {
doWork(data: string[]): string[] {
return data.sort().reverse();
}
}
const context = new Context(new AscendingStrategy());
context.doStrategyWork();
context.setStrategy(new DescendingStrategy());
context.doStrategyWork();