-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrategy.ts
44 lines (35 loc) · 1.09 KB
/
strategy.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
(function () {
class Context {
private strategy: IStrategy;
constructor(strategy: IStrategy) {
this.strategy = strategy;
}
setStrategy(strategy: IStrategy) {
this.strategy = strategy;
}
execute(a: number, b: number) {
console.log('Контекст делегирует выполнение функции стратегии');
this.strategy.execute(a, b);
}
}
interface IStrategy {
execute(a: number, b: number): void,
}
class SumStrategy implements IStrategy {
execute(a: number, b: number) {
console.log(a + b, 'Стратегия суммирования');
}
}
class DiffStrategy implements IStrategy {
execute(a: number, b: number) {
console.log(a - b, 'Стратегия разности');
}
}
const sum = new SumStrategy();
const context = new Context(sum);
context.execute(2, 3);
const diff = new DiffStrategy();
context.setStrategy(diff);
context.execute(2, 3)
}
)();