Mark As Completed Discussion

Strategy

The Strategy pattern helps define a family of related algorithms, and make decisions to use one or another based on user input when the application runs.

One benefit of using Strategy is that it helps avoid complex chains of conditions for switching between algorithms, replacing them with delegation to different Strategy objects.

For example, in an order processing system, prices will probably be calculated in different ways depending on customer type, purchase quantity, and other factors. In this situation, using Strategy can help select the right pricing algorithm at runtime.

Another example would be a tennis game where defence and offence are two distinct strategies:

1class IMatchStrategy 
2{
3    hitTheBall() {}
4}
5
6class DefensiveMatchStrategy extends IMatchStrategy
7{
8    hitTheBall()
9    {
10        return { 
11            Type : "Slice",
12            Power: 0.7
13        }
14    }
15}
16
17class AggressiveMatchStrategy extends IMatchStrategy
18{
19    hitTheBall()
20    {
21        return {
22            Type : "Flat",
23            Power: 1.2
24        }
25    }
26}

At call site, we can start a match aggressively, but then switch to defense depending on external factors:

1let match = new Match(new AggressiveMatchStrategy());
2
3let shot1 = match.hitTheBall();
4
5console.log(match.matchStrategy);
6console.log(shot1.toString());
7
8if (Math.floor(Math.random() * (10 - 1) + 1) > 5)
9    match.matchStrategy = new DefensiveMatchStrategy();
10
11let shot2 = match.hitTheBall();
12
13console.log(match.matchStrategy);
14console.log(shot2.toString());

A popular technique related to the Strategy pattern is Dependency Injection.