7
Back to Boss Battles

StrategyVSState

The Problem

Scenario A β€” Strategy territory: You are building a pricing engine. Each customer tier (free, premium, enterprise) calculates discounts differently. The caller picks which pricing algorithm to use based on the customer's current tier at checkout time. The algorithm does not change the tier.

Scenario B β€” State territory: You are building an order management system. An order moves through states: draft, pending-payment, paid, shipped, delivered, cancelled. The behaviour of every method (cancel(), ship(), refund()) changes depending on the current state, and calling a method can change the state itself.


Why They Look Alike

Both patterns extract behaviour into separate classes behind a common interface and let the context delegate to the current one. The UML class diagrams are nearly identical:

Rendering diagram…

Replace "Strategy" with "State" and "setStrategy" with "setState" and the diagram is the same. That is why people confuse them.


The Fundamental Difference

Strategy: the client chooses which algorithm to use. State: the object transitions itself.

In Strategy the caller says "use algorithm X." In State the object is in state Y and after an action it decides internally to move to state Z.


Decision Rule

Clue in the requirementsPattern
"The user/caller picks which X to use"Strategy
"Behaviour depends on current mode/phase/lifecycle"State
"Algorithm is interchangeable at call-time"Strategy
"Calling a method can change how future calls behave"State
"No memory between calls"Strategy
"There are legal/illegal transitions"State

Short version: Who picks? External = Strategy. Internal = State.


Side-by-Side Code

Strategy β€” pricing algorithm chosen by caller

typescript
1interface PricingStrategy {
2 calculateDiscount(subtotal: number): number;
3}
4
5class FreeTierPricing implements PricingStrategy {
6 calculateDiscount(subtotal: number): number {
7 return 0; // no discount
8 }
9}
10
11class PremiumPricing implements PricingStrategy {
12 calculateDiscount(subtotal: number): number {
13 return subtotal * 0.1; // 10%
14 }
15}
16
17class CheckoutService {
18 constructor(private strategy: PricingStrategy) {}
19
20 // Caller can swap the strategy at any time
21 setStrategy(s: PricingStrategy) {
22 this.strategy = s;
23 }
24
25 checkout(subtotal: number): number {
26 const discount = this.strategy.calculateDiscount(subtotal);
27 return subtotal - discount;
28 }
29}
30
31// Usage β€” the CALLER decides which strategy
32const service = new CheckoutService(new FreeTierPricing());
33service.checkout(100); // 100
34service.setStrategy(new PremiumPricing());
35service.checkout(100); // 90

State β€” order transitions itself

typescript
1interface OrderState {
2 pay(order: Order): void;
3 ship(order: Order): void;
4 cancel(order: Order): void;
5}
6
7class PendingPaymentState implements OrderState {
8 pay(order: Order): void {
9 console.log("Payment received.");
10 order.setState(new PaidState()); // state changes ITSELF
11 }
12 ship(_order: Order): void {
13 throw new Error("Cannot ship β€” not paid yet.");
14 }
15 cancel(order: Order): void {
16 console.log("Order cancelled.");
17 order.setState(new CancelledState());
18 }
19}
20
21class PaidState implements OrderState {
22 pay(_order: Order): void {
23 throw new Error("Already paid.");
24 }
25 ship(order: Order): void {
26 console.log("Order shipped.");
27 order.setState(new ShippedState());
28 }
29 cancel(order: Order): void {
30 console.log("Refunding and cancelling.");
31 order.setState(new CancelledState());
32 }
33}
34
35class ShippedState implements OrderState {
36 pay() { throw new Error("Already paid."); }
37 ship() { throw new Error("Already shipped."); }
38 cancel() { throw new Error("Cannot cancel β€” already shipped."); }
39}
40
41class CancelledState implements OrderState {
42 pay() { throw new Error("Order is cancelled."); }
43 ship() { throw new Error("Order is cancelled."); }
44 cancel() { throw new Error("Already cancelled."); }
45}
46
47class Order {
48 private state: OrderState = new PendingPaymentState();
49
50 setState(s: OrderState) { this.state = s; }
51 pay() { this.state.pay(this); }
52 ship() { this.state.ship(this); }
53 cancel() { this.state.cancel(this); }
54}
55
56// Usage β€” the ORDER decides its own transitions
57const order = new Order();
58order.pay(); // "Payment received." β†’ now PaidState
59order.ship(); // "Order shipped." β†’ now ShippedState
60order.cancel(); // Error: "Cannot cancel β€” already shipped."

Key difference in the code:

  • Strategy: service.setStrategy(new X()) β€” the caller picks.
  • State: order.setState(new PaidState()) β€” the state object picks the next state.

Scenario Quiz

?Knowledge Check

1A file export service lets the user choose between CSV, JSON, or XML format. The format selection happens at the API endpoint. Which pattern?

2A payment transaction goes through states: initiated β†’ authorized β†’ captured β†’ settled. Each state has different rules for what operations are allowed. Which pattern?

3A rate limiter can use token-bucket, sliding-window, or fixed-window algorithm. The admin configures which one. Which pattern?

4A CI/CD pipeline has stages: build β†’ test β†’ deploy. If build fails, it skips test and deploy. If test fails, it skips deploy. Which pattern?

5A reporting module generates charts. The user picks bar, line, or pie. The chart type doesn't affect future chart requests. Which pattern?

6A WebSocket connection can be: connecting, open, closing, closed. Sending a message is only valid in 'open'. Which pattern?

7A caching layer supports LRU, LFU, or FIFO eviction. The policy is set at startup and never changes. Which pattern?

8A music player has states: stopped, playing, paused. Pressing 'play' from stopped starts the song, from paused resumes it. Which pattern?