Strategy

GoF Definition

Define a family of algorithms, encapsulate each one, and make them interchangeable.

Strategy lets the algorithm vary independently from clients that use it.

In other words, the strategy pattern defines a family of strategies or algorithms. Each algorithm is encapsulated in its own class. The different algorithms forming the family can be used in an interchangeable way. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.

  • The IStrategy interface is implemented by two strategy classes—Strategy1 and Strategy2. These two classes encapsulate different strategies that are interchangeable. They form a family of algorithms.

  • The Context class holds an instance of one of the implementations of IStrategy

  • Context class has a method called Process() which calls Algorithm() method.

Real world example:

Let's say you have content to be encrypted. Now depending on content, source, destination and receiver you would like to use specific algorithm for encryption.

We do not know what type of content and its properties before hand. At run time after evaluating the content and properties specific algorithm has to be used. So strategy pattern comes handy here.