Skip to content

Design Patterns

Strategy

Choosing and running a strategy takes O(1) time (constant time) plus whatever that strategy itself costs.

The idea, in plain English

The strategy pattern lets you swap out how something gets done, on the fly. Think of a map app choosing between driving, walking, or biking directions. The goal — getting there — stays the same, but you can pick a different method any time.

How it works

  1. 1Define several methods that can swap in for each other and do the same kind of job.
  2. 2Store or pass in which one to use.
  3. 3Call it through one shared entry point. Swapping the method changes the behavior, and you don't rewrite the calling code.

When you'd use it

Use this when you have several ways to do one thing — sorting orders, payment methods, or pricing rules — and want to switch between them cleanly.

Common beginner mistakes

  • Don't hardcode one behavior with if/else everywhere. Swap strategies instead.
  • Give every strategy the same inputs and outputs, so you can truly swap them for each other.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
add: 7
multiply: 12

Not sure this is the right topic? See the learning paths → or where this leads →