Sunday, February 10, 2019

Strategy pattern

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Category:
Behavioral design pattern

The problem to solve:
Suppose we have many kinds of ducks. They can fly in many ways and can quack in many ways. The trivial way to solve it is to use inheritance. There can be interfaces like Flyable and Quackable. The concrete duck implementations can implement the Flyable and Quackable interfaces. The problem here is that several ducks can have same fly behavior or quack behavior. Code will be duplicated in such cases.

Solution:
Composition is used to solve the problem. There will be interfaces for Fly behavior and Quack behavior. Concrete implementations of Fly behavior and Quack behavior will be treated as family of algorithms. The concrete duck implementations will be composed of Fly behavior and Quack behavior interfaces.

Code Example:
Head first duck example is good. Springframework guru has shown a good example also.

UML:
The following UML diagram is from Head First Design Pattern book:


Where to apply:
  • Use the Strategy pattern when you want to use different variants of an algorithm within an object and be able to switch from one algorithm to another during runtime.
  • Use the Strategy when you have a lot of similar classes that only differ in the way they execute some behavior.
  • Use the pattern to isolate the business logic of a class from the implementation details of algorithms that may not be as important in the context of that logic.
  • Use the pattern when your class has a massive conditional operator that switches between different variants of the same algorithm.

Associated design principles:
  • Identify the aspects of your application that vary and separate them from what stays the same. Encapsulate what varies.
  • Favor composition over inheritance.
  • Program to an interface, not an implementation.

Pros:
  • Prevents the conditional statements. (switch, if, else…)
  • The algorithms are loosely coupled with the context entity. They can be changed/replaced without changing the context entity.
  • Very easy extendable.
  • Allows hot swapping algorithms at runtime.
  • Isolates the code and data of the algorithms from the other classes.
  • Replaces inheritance with delegation/composition

Cons:
  • Clients must know existence of different strategies and a client must understand how the Strategies differ. Client must be aware of the differences between strategies to pick a proper one.
  • It increases the number of objects in the application. Increases overall code complexity by creating multiple additional classes.

References:

No comments:

Post a Comment