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.
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
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
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.
move() into EatStrategy and MoveStrategy interfaces, and the Animal class has properties of these strategies as the following diagram.
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);
Top comments (0)