Practicing Strategy Pattern with TypeScript

Hello everyone, how is it going. It’s has been a long time since the last time I updated my blog. At the moment I’m so busy with my research and studying. There are so many things to learn, especially Deep Learning and Mathematics.

I have built my Mobile App for about 1 week, and React-Native is quite interesting. It’s so fast to build an application comparing to Swift and Java. But the cons is, obviously, it uses JavaScript lol. Even my first programming language is JavaScript I have to admit that I don’t like it very much. The language is easy to adopt, but when our applications got big, the management becomes very confusing.

So I decided to re-write my React-Native app with TypeScript, which is just JavaScript with static typing. I’m glad that it’s a OOP language(not like Go), so I can apply my knowledge in OOP principles and Design Patterns.

This series is about how to apply Design Patterns in TS. And this, the first article of the series, is about Strategy Pattern.

Strategy Pattern

The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Example

 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
interface FlyBehavior {
  fly();
}

interface QuackBehavior {
  quack();
}

class FlyHigh {
  fly() {
    console.log('I am flying so high');
  }
}

class NotFly {
  fly() {
    console.log('Okay no flying');
  }
}

class QuackLoud {
  quack() {
    console.log('QUACK QUACK');
  }
}

class SilentQuack {
  quack() {
    console.log('....');
  }
}

class Duck {
  flyBehavior: FlyBehavior;
  quackBehavior: QuackBehavior;
  setFlyBehavior(fb: FlyBehavior) {
    this.flyBehavior = fb;
  }
  setQuackBehavior(qb: QuackBehavior) {
    this.quackBehavior = qb;
  }
  performQuack() {
    this.quackBehavior.quack();
  }
  performFly() {
    this.flyBehavior.fly();
  }
  display() {}
}

class Donald extends Duck {
  constructor() {
    super();
    this.flyBehavior = new NotFly();
    this.quackBehavior = new QuackLoud();
  }
  display() {
    console.log('Hello I Am Donald');
  }
}

const donald: Duck = new Donald();

donald.display();

donald.performFly();

donald.performQuack();

donald.setFlyBehavior(new FlyHigh());

donald.performFly();

With Strategy pattern, our code will be more flexible, and client and even change their algorithms at run time