GoF Design Patterns – Strategy


The Strategy Design Pattern is a behavioral design pattern used to encapsulate family of algorithms. Each one of them is made interchangeable within a particular context. This pattern enables the client to choose from a set of algorithms dynamically, based on specific needs or requirements. The Strategy pattern is useful when multiple variations of an algorithm or behavior are required, and when these variations need to be easily swapped.

For example, let’s say that we develop an e-commerce application. In the domain model, we need to create a shopping cart, which needs to be able to calculate the total cost, including total products and shipping costs. Shipping cost calculation is dependent on whether we do domestic or international shipping. Therefore, we need to structure our code in a way so that the shipping cost calculation strategy can be easily and dynamically swapped. Such a structure can be achieved using the Strategy Design Pattern:

In the above example, delivery cost calculation is encapsulated in each strategy, and the shipping strategy can be dynamically switched on the shopping cart.

More on this pattern…

To read more on this and the other patterns, get “GoF Design Patterns Distilled” book from Amazon or Leanpub: