Strategy

Motivation

Many algorithms exists for making online payments. Hard-wiring all such algorithms into the classes that require them isn't desirable for several reason:

  • Putting payment code into clients classes that need it, make them complex. It becomes more bigger and harder to maintain of client supports multiple payment algorithms.

  • It is obvious that client will be using one algorithm at a time and different at other time. So putting code for all algorithm into client even only one is getting used at a time.

  • It is difficult to add new algorithm or use existing algorithm for other client.

These problems can be avoided by defining classes that encapsulates different online payment algorithms. An algorithm that's encapsulated in this way is called a strategy.

Applicability - When to use Strategy pattern

  • Many related classes differ in only their behavior.

  • Different variants of an algorithm are required.

  • An algorithm uses data that client shouldn't know about.

  • A class defines many behaviors which are mainly multiple conditional statements.

Also known as

Policy

Intent

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. [i.e. Defines a set of encapsulated algorithms that can be swapped to carry out a specific behavior.]

- Gang of four