Design Patterns

Strategy Pattern

The Strategy pattern explained: one job, swappable behaviours. A Python example, swapping at runtime, functions as strategies, and when a plain if is better.

  • 6 min read
  • 5 questions
  • +35 XP
Transcript

Strategy pattern explained by cats. Kitty loves to hunt. Sometimes she attacks, sometimes she sneaks, sometimes she hides and waits. The goal is the same. Catch the toy mouse. But the tactic changes. That's the strategy pattern. You define one action, let's say hunt.

Then you plug in different strategies, like attack, sneak, or wait. Kitty can swap tactics at runtime. No need to rewrite the hunt method. Calls a strategy interface. Each tactic such as attack, sneak, wait, implements that interface. Switch strategies on the fly.

Strategy pattern is having the same goal, but different behaviors. Perfect when you need flexible, swappable algorithms. That's the strategy pattern.