Strategy Pattern
An easy way to change behaviour at runtime. Explanation and implementation.
What is the strategy design pattern?
The strategy design pattern is rather simple. It's all about changing behaviour at runtime. For example, imagine you're playing a game and your character unlocks wings, allowing it to fly. The behaviour changed. This pattern allows for new behaviour without having to change the code too much.
Example: if later on our wings sustain damage, we could add a HalfWingFly class which limits the duration of flight. Our class is easily expandable because of the strategy design pattern, making it future proof.
UML and Code Example
As we can see, we have an interface called Fly and two classes, CanFly and NoFly. Both classes implement the fly method, each defining its specific behaviour. The Player class uses Fly association to determine whether it can fly and how it flies. It regulates this behaviour using a setter.
// Player Class -- using the strategy design pattern
public class Player {
Fly flyBehaviour;
public void setFlyBehaviour(Fly behaviour) {
this.flyBehaviour = behaviour;
}
public Player() {
setFlyBehaviour(new NoFly());
}
public void useFlyAbility() {
flyBehaviour.fly();
}
}
Using this code, if the player later on unlocks the ability to fly, we can use the setter and assign the CanFly behaviour.
Conclusion
You should use the strategy design pattern when you want to change behaviour at runtime or if you depend on a condition. For example, if you have a layout system on a website, and load components based on roles (e.g. admin, premium user), you could load different ones based on that.