DEV Community

Ed is Taking Note
Ed is Taking Note

Posted on • Updated on

[Design Pattern] Strategy Pattern

Strategy pattern is a group of algorisms or business logics and each of them are interchangable.
Strategy pattern separates the algorisms from the clients that use it so that we can modify the algorisms without touching the clients.

Scenario Problem

Here is the simple example. We have an Animal class, and 4 different child classes(Horse, Sheep, Lion, and Bird) inherit from it.

It may be very straightforward to implement eat() and move() methods in each of the children classes. However, sometimes some of the children classes may have the same implementation.

As we see this example, Horse and Sheep have the same eat() behavior(Eat grass); Horse, Sheep, and Lion have the same move() behavior(Walk).
Now this code duplication shows some bad smells while we have only 4 classes. Imagine how crazy it will be if there's like 10 classes or more? 🤯


Now the strategy pattern comes in.
We change eat() and move() into EatStrategy and MoveStrategy interfaces, and the Animal class has properties of these strategies as the following diagram.
Image description

We now separate the eat and move behaviors from the Animal class. The benefit is when we modify any of the move or eat behaviors(the business login), we don't have to touch the animal(the client using it) like before. Also, we will not have any duplicated codes.

Final code will be like:

MoveStrategy walk = new WalkStrategy();
MoveStrategy fly = new FlyStrategy();
EatStrategy eatGrass = new EatGrassStrategy();
EatStrategy eatMeat = new EatMeatStrategy();
EatStrategy eatGrains = new EatGrainsStrategy();

Animal horse = new Animal(walk, eatGrass);
Animal sheep = new Animal(walk, eatGrass);
Animal sion = new Animal(walk, eatMeat);
Animal bird = new Animal(fly, eatGrain);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)