Strategy & State Patterns0%
Strategy & State Patterns
Beginner12 min read•Updated: Jul 11, 2026
Strategy & State Patterns in Modern JavaScript
As business logic expands, conditional statements (if...else if...else or massive switch blocks) become unmaintainable anti-patterns. The Strategy Pattern and the State Pattern replace conditional branching with polymorphic object delegation.
1. The Strategy Pattern
The Strategy Pattern defines a family of interchangeable algorithms, encapsulates each one into a separate object, and makes them swappable at runtime.
The Problem: Massive Conditional Branching
JavaScript
// ANTI-PATTERN: Hard to maintain, violates Open/Closed Principle
function calculateShipping(order, carrier) {
if (carrier === 'fedex') return order.weight * 1.5 + 5;
if (carrier === 'ups') return order.weight * 1.8 + 2;
if (carrier === 'dhl') return order.weight * 2.2 + 8;
// Adding new carrier requires editing this function!
}
The Strategy Solution:
JavaScript
// Strategy 1: FedEx
const fedexStrategy = {
calculate: (weight) => weight * 1.5 + 5
};
// Strategy 2: UPS
const upsStrategy = {
calculate: (weight) => weight * 1.8 + 2
};
// Strategy 3: DHL Express
const dhlStrategy = {
calculate: (weight) => weight * 2.2 + 8
};
// Context Object
class ShippingCalculator {
constructor(strategy) {
this.strategy = strategy;
}
setStrategy(strategy) {
this.strategy = strategy;
}
calculateCost(order) {
return this.strategy.calculate(order.weight);
}
}
// Swapping strategies dynamically at runtime:
const shipping = new ShippingCalculator(fedexStrategy);
console.log('FedEx Cost:', shipping.calculateCost({ weight: 10 })); // $20
shipping.setStrategy(dhlStrategy);
console.log('DHL Cost:', shipping.calculateCost({ weight: 10 })); // $30
2. The State Pattern
The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
Media Player State Machine Example:
Output
┌──────────────┐
┌────►│ PausedState │◄────┐
Play │ └──────┬───────┘ │ Pause
│ │ Play │
┌────┴──────┐ ▼ ┌─────┴─────┐
│StoppedState│ │PlayingState│
└───────────┘ └───────────┘
JavaScript
class PlayingState {
constructor(player) { this.player = player; }
play() { console.log('Already playing audio.'); }
pause() {
console.log('Pausing audio playback.');
this.player.setState(this.player.pausedState);
}
}
class PausedState {
constructor(player) { this.player = player; }
play() {
console.log('Resuming audio playback.');
this.player.setState(this.player.playingState);
}
pause() { console.log('Already paused.'); }
}
class AudioPlayer {
constructor() {
this.playingState = new PlayingState(this);
this.pausedState = new PausedState(this);
// Initial state: Paused
this.currentState = this.pausedState;
}
setState(state) {
this.currentState = state;
}
play() { this.currentState.play(); }
pause() { this.currentState.pause(); }
}
const player = new AudioPlayer();
player.play(); // "Resuming audio playback."
player.play(); // "Already playing audio."
player.pause(); // "Pausing audio playback."
3. Key Difference Between Strategy & State
| Dimension | Strategy Pattern | State Pattern |
|---|---|---|
| Intent | Change how an operation is accomplished (algorithm swapping) | Change what the object does based on internal lifecycle state |
| Awareness | Strategies are generally unaware of each other | State objects frequently trigger transitions to neighboring states |
| Client Control | Client chooses and injects the strategy | Transitions occur internally as actions execute |
Interactive Quiz
Practice Quiz
Question 1
What software engineering principle is best satisfied by the Strategy Pattern?
Question 2
What is the primary characteristic of the State Pattern?
Question 3
How does the Strategy pattern eliminate massive if/else chains?
Question 4
In the State pattern, who typically manages transitions between states?
Question 5
Can the active strategy in a context object be changed at runtime?
Next Lesson
Proxy & Decorator Patterns
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Observer & Pub/Sub Pattern | Proxy & Decorator Patterns |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.