Sitemap

Strategy design pattern

2 min readJan 19, 2020

--

Press enter or click to view image in full size
Image credits:https://www.smartva.net/

What is Strategy design pattern?

  • It is behavioural design pattern. This pattern is also referred as Policy pattern.
  • This pattern lets us define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.
  • This pattern is useful to when there are different algorithms to choose at runtime depending upon user selection/context.
  • Same behaviour(end result) however different ways to achieve it.

Real world analogy:

  • Consider example of project management.
  • To achieve this, there are different strategies/methodologies to choose from. However, main behaviour/end goal is better project management.
  • There could be various strategies like Scrum, Kanban, Lean,Waterfall and many more.

Example in software/apps development:

  • Consider scenario of Payment processing within mobile application.
  • We can infer that there is one behaviour payment that needs to be achieved. However, there are multiple ways/payment mechanisms to complete payment.
  • For example, payment can be done using CreditCard , DebitCard or any other mobile wallet APIs. Ultimate goal is to pay specific amount in a specified currency.
  • Sample code in swift: https://github.com/ParthContractor/StrategyDesignPattern

Get Parth’s stories in your inbox

Join Medium for free to get updates from this writer.

Benefits:

  • More isolated, understandable and readable code.
  • Adherence to Open/Closed principle.
  • Changing algorithms/strategies at runtime is easy.

Drawbacks:

  • There could be possibility of increased distinct strategies over the period of time and apparently cumbersome to handle/manage them all.
  • Clients must understand all strategies to properly utilised one over another at runtime.

Comparison with Template method pattern:

  • Template method depends upon single algorithm in abstract super class and allowing concrete subclasses to override part of steps.
  • However, Strategy design pattern enables selection of algorithm at runtime. Different strategy is applied to object at runtime to achieve its specific behaviour.

Other interesting articles/reference materials:

Summary:

Strategy pattern is useful when you want to decide during run time how you want to run a particular behaviour from set predefined ways.

--

--

Parth
Parth

Written by Parth

Principal Software Engineer