Strategy Pattern

Put each way of doing a job in its own object behind one interface, so the caller can swap the way without changing its own code.

Overview

The Strategy pattern is one of the behavioral patterns in Design Patterns (Gamma, Helm, Johnson and Vlissides, 1994). When there are several ways to do one job, such as several ways to price shipping, sort a list or compress a file, you give each way its own class with the same interface. The code that needs the job done, the context, holds one of those objects and calls it. Which one it holds can be decided when the context is built, or changed later, and the context's code never changes.

Strategy is probably the most used pattern in everyday code, often without the name. Every sort that takes a comparator or a key function is a strategy. Interviewers ask about it to see whether you can replace a growing chain of conditionals with objects, whether you know when a plain function is enough, and whether you can tell Strategy from the patterns that look like it: State and Template Method.

The problem it solves

A checkout computes the shipping cost. First there is a flat rate. Then a per-kilo rate for heavy parcels. Then free shipping over a threshold, then a rate per country. Each rule is an if in one growing function; each new rule means editing and re-testing that function, and the rules cannot be tested on their own.

Strategy changes four things about that function. In the conditional chain, all the rules live in one function; with Strategy, each rule is one small class. In the chain, a new rule edits tested code; with Strategy, a new rule is a new class and the context is untouched. In the chain, the rules cannot be tested alone; with Strategy, each one is tested by itself. And in the chain, the rule is fixed by whichever branch runs, while a strategy is an object that can be chosen, stored or passed around.

Interview questions

  • Show how Strategy removes a conditional chain. What does it cost?
  • How is Strategy different from Template Method?
  • How is Strategy different from State? The class diagrams look identical.
  • When is a function enough, and when do you want a strategy class?
  • Design a pricing system with several discount rules that must combine.

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio