Design patterns are better understood when we try learning them with an example. Lets take up a problem here.
Lets say there are Animals which can fly and those which cannot. Since, the world is constantly evolving, any animal can be given the ability to fly by nature, or the ability can be taken from the animal.
The problem that the great mathematician ‘Nature’ faces here is, ‘How to incorporate a new behavior of flying within the present evolution scenario?’. Nature will have to ensure that the flying abilities can be altered and changed with time, in order to ensure that evolution is not compromised.
Steps nature followed –
- Prepare various flying algorithms (NoFlyingAbility, SparrowLikeFylingAbility, EagleLikeFlyingAbility) under a common interface FlyingAbility.
- The FlyingAbility interface was added to Animal abstract class. This means that Animals can now have FlyingAbiltiy.
- A public setter of FlyingAbility in Animal ensures that evolution can surely update the flying capabilities of the Animals.
This pattern is called StrategyPattern as the nature decides the strategy an animal will use to fly.
Download the coded implementation
Pros and Cons
- The algorithms and behaviors can be reused.
- The algorithms are loosely coupled with the context entity. They can be changed/replaced without changing the context entity.
- Prevents the conditional statements.
- Client must be aware of the various strategies, thus helping him decide the best strategy.
- It increases the number of objects in the application.