Strategy Pattern
Swap interchangeable algorithms behind a shared interface at runtime without rewriting the caller.
1. Intent
Extract a family of interchangeable algorithms into separate units behind one interface, so a Context can swap how it performs a task at runtime without conditional branching.
2. Problem
Suppose you are building a deployment runner for a platform team. At first it only performs rolling updates. Later, product teams ask for blue-green cutovers for zero-downtime databases, and canary rollouts that shift 10% of traffic before full promotion.
If all three rollout algorithms live inside DeployRunner behind an if/else or switch statement, every new rollout mode forces you to edit and retest the core runner. The class grows hard to read, and unrelated deployment logic becomes tightly coupled.
3. Solution
Define a common DeployStrategy interface with a single execute(release) method. Move each rollout algorithm into its own class (RollingStrategy, BlueGreenStrategy, CanaryStrategy) implementing that interface.
DeployRunner (the Context) holds a reference to a DeployStrategy and delegates the rollout step to it. The caller decides which strategy to inject or swap at runtime, so DeployRunner never needs to know which rollout algorithm is active.
4. Real-world analogy
5. Flow: watch it work
Strategy Pattern: DeployRunner → DeployStrategy
Press Start or tap any step dot to trace the path.
▸All steps (8)
6. Structure
7. Code
interface Release {
service: string;
version: string;
}
interface DeployResult {
mode: string;
summary: string;
}
// Strategy interface
interface DeployStrategy {
execute(release: Release): Promise<DeployResult>;
}
// Concrete strategies
class RollingStrategy implements DeployStrategy {
constructor(private readonly maxUnavailable = 1) {}
async execute(release: Release): Promise<DeployResult> {
return {
mode: 'rolling',
summary: `Rolled out ${release.service}@${release.version} (maxUnavailable=${this.maxUnavailable})`,
};
}
}
class BlueGreenStrategy implements DeployStrategy {
async execute(release: Release): Promise<DeployResult> {
return {
mode: 'blue-green',
summary: `Booted green environment for ${release.service}@${release.version} and switched router`,
};
}
}
class CanaryStrategy implements DeployStrategy {
constructor(private readonly trafficPercent: number) {}
async execute(release: Release): Promise<DeployResult> {
return {
mode: 'canary',
summary: `Shifted ${this.trafficPercent}% traffic to ${release.service}@${release.version}`,
};
}
}
// Context
class DeployRunner {
constructor(private strategy: DeployStrategy) {}
setStrategy(strategy: DeployStrategy): void {
this.strategy = strategy;
}
async deploy(release: Release): Promise<DeployResult> {
return this.strategy.execute(release);
}
}
// Usage: swap strategies at runtime
const runner = new DeployRunner(new RollingStrategy(2));
await runner.deploy({ service: 'api', version: '1.4.0' });
runner.setStrategy(new CanaryStrategy(10));
await runner.deploy({ service: 'api', version: '1.5.0-rc1' });8. When to use / when to avoid
- You need to swap how an object performs a task at runtime (e.g. rolling vs canary deploy, compression codec, or retry backoff).
- A class has a growing switch/if-else block selecting between variants of the same operation.
- You want to isolate complex algorithm state (like canary traffic percentages) from the caller.
- You only have two simple variants that rarely change—a plain conditional is easier to read.
- Strategies are stateless one-liners; pass a plain callback function instead of creating classes.
- Callers have no reason to know the difference between strategies—hide the choice inside a factory.
When NOT to use it
Overengineering shows up when every single if statement gets turned into a Strategy interface plus three single-method classes. If you have two branches that are three lines each and have not changed in a year, keep the if/else. In TypeScript, if a strategy has no configuration or internal state, a function parameter ((input) => output) gives you the exact same decoupling with zero class ceremony.
Real-world example in this stack
In this site's diagram renderer (components/diagram/layout.ts), the layout engine switches between 'flow' (dagre left-to-right or top-to-bottom) and 'tree' (hierarchical bus layout) via FlowLayoutMode without duplicating the node and edge rendering components.
9. How to implement
Spot the varying algorithm
Find the method or conditional block inside your Context class that changes frequently or supports multiple modes.
Declare the Strategy interface
Define a small contract (often one method, or a TypeScript function type) with only the inputs the algorithm needs.
Extract Concrete Strategies
Move each branch into its own class or function implementing the Strategy interface.
Inject and delegate from the Context
Store the Strategy reference on the Context (via constructor or setter) and delegate execution to it.
10. Pros / Cons
- Swap algorithms at runtime without editing the Context.
- Follows Open/Closed Principle: add new strategies without touching existing ones.
- Isolates algorithm-specific config and state (like canary weights) from core orchestration.
- Adds extra types and files if used for trivial, stable conditionals.
- Clients must understand how strategies differ in order to pick the right one.
11. Relations
Both compose an interface, but Strategy swaps one algorithm on a single Context while Bridge separates two independent class hierarchies.
Same class diagram, different intent: in Strategy the client picks the strategy; in State the state objects transition the Context automatically.
Strategy replaces the inner algorithm; Decorator wraps an object to layer extra behavior before or after the call.
12. Check yourself
Check Yourself
1. Who is responsible for selecting which concrete Strategy a Context uses?
2. When is a TypeScript function type preferable to a Strategy class hierarchy?
Sources
- TypeScript Handbook: More on Functions
- Refactoring.Guru: Strategy Pattern
- Dive Into Design Patterns (Alexander Shvets), chapter "Behavioral Design Patterns: Strategy"
Related Notes
Observer Pattern
Notify multiple subscribers automatically when a subject's state changes, without coupling the subject to concrete listeners.
Pattern Relations: Bridge vs Adapter vs Strategy vs Decorator vs State
Five patterns that share composition and interface delegation—how their intents, lifecycles, and trade-offs differ.