Strategy Design Pattern

In the series of behavioral design patterns, Strategy pattern is one of the most widely used patterns. It’s a good example of Open Closed Design Principle of SOLID object oriented design principles.To understand it more, let’s find out first what is “Strategy Pattern?”

Definition:

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

The strategy pattern defines a family of related algorithms e.g. sorting algorithms like bubble sort, quicksort, insertion sort and merge sort, or compression algorithm e.g. zip, gzip, tar, jar, encryption algorithm e.g. 128 bit Encryption, AES. SHA etc. and lets the algorithm vary independently from clients that use it.

For example, Strategy pattern can be used to sort numbers and allows client to choose any sorting algorithm at run time, without modifying the class itself. Therefore, Strategy pattern provides flexibility, extensibility, and choice. You should consider using this pattern when you need to select an algorithm at runtime.

Example:

Let’s say you have a text to encrypt. The goal is to select encrypting algorithms based on their performance i.e. how efficiently they encrypt small or long text.

At the outset, it should be opaque to the user how data is encrypted or in principle which data structure is used internally to encrypt the data. Therefore, the question lies in the fact how to design a solution that differs only in their behavior. In fact, in this case, we need different variant of encryption algorithms.

Solution:

Strategy design pattern provides solutions to the aforementioned problem description. It helps to avoid exposing complex, algorithm-specific data structures.

structures

Participants:

EncryptionAlgorithm (Abstract Strategy)

  • Declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by ConcreteStrategy.
ConcreteStrategy (_128BitEncryption, ShaEncryption)
  • Implement the algorithms using the strategy interface.
Context
  • Is configured with a ConcreteStrategy object.
  • Maintains a reference to a Strategy object.
  • May define an interface that lets Strategy access its data.
Strategy and context interact to implement the chosen algorithm. A context may pass all the data required by the algorithm to the strategy when the strategy is called.

A context forwards requests from its clients to its strategy. Clients usually create and pass a ConcreteStrategy object to the context; thereafter, clients interact with the context exclusively.

So to summarize, hierarchies of strategy define a family of algorithms or behaviors for context to reuse. The strategy pattern offers an alternative to conditional statement for selecting desired behavior.


Similar Articles