Stratety pattern defines a group of algorithms, encapsulates each one and makes the interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
When designing the application identify the aspects that:
– stay the same – then use inheritance so the subclasses reuse the code from superclass
– varies, then separate (encapsulate) them
These vary parts can then be changed or extended without affecting the ones that don’t change.
It is not a good practice to use inheritance in case of varying parts since,e.g. if someone creates an abstract method in super class, then every super class is forced to implement (or provide empty impl) even if this method is not used at all.
Composition (has-a relationship) gives more flexibility, not only lets you encapsulate different implementations of a interfaced behavior (algorithms), but it also allows to change the behavior at runtime (via setters injecting new interfaced implementation and delegating the call to that impl).
Strategy pattern is an alternative to inheritance – where you are stuck with the behavior of the subclass even if you need to change it. With the strategy pattern you can configure different classes with different behavior by composing with a different object.
The main class contains a instance variable of the type of an interface that different algorithms implement. The main class has a setter method to assign the reference to that variable to a particular algorithm implementation. The call to the method of the main class will be delegated to the interfaced method of the concrete algorithm class.
The state pattern allows you get rid of many conditional statements and encapsulate behaviors into state objects. When you change the state object, the behavior will change.
The state and strategy patterns have the same class diagram, but they differ in intent:
– strategy configures context with a behavior/algorithm
– state allows context to change its behavior as its state changes