The name of the pattern always sounded misleading to me – there is no mystical sophisticated strategy that you need to apply to use this pattern.
This is all about substituting plain object oriented inheritance with neatly encapsulated algorithms.
So, instead of inheriting a behaviour from parent class, we provide a behaviour on instance creation.
Why use strategy pattern?
It promotes reusing of the code and solves issues with horizontal inheritance (when several classes on the same level has the same interface, but would like to implement it differently). I also like an elegant way of keeping the implementation of the algorithm in one place.
Here is an example of strategy pattern code:
public class Area52 {
public class Duck {
private IQuackBehaviour quackBehaviour;
private IFlyBehaviour flyBehaviour;
public Duck(IQuackBehaviour quackBehaviour, IFlyBehaviour flyBehaviour) {
this.quackBehaviour = quackBehaviour;
this.flyBehaviour = flyBehaviour;
}
public void quack() {
this.quackBehaviour.quack();
}
public void fly() {
this.flyBehaviour.fly();
}
}
public static void main(String[] args) {
Duck wildDuck = new Duck(new LoudQuackBehaviour(), new LowFlyBehaviour());
Duck mountainDuck = new Duck(new LoudQuackBehaviour(), new HighFlyBehaviour());
Duck rubberDuck = new Duck(new SqueakyQuackBehaviour(), new NoFlyBehaviour());
}
}
As you can see, each duck can quack and fly (even though rubberDuck implementation of flying is… not flying). We reuse the behaviours, we keep them clean in a separate classes (not included in the code example). No inheritance problems – neat and simple.
A huge thank you to Christopher Okhravi for his series on design patters. His video on Strategy Pattern inspired me to write this post to recall and revisit all the patterns: https://www.youtube.com/watch?v=v9ejT8FO-7I

from: https://cottagelife.com/general/ontario-to-host-worlds-largest-rubber-duck/
