Strategy vs State
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's order has a payment method the customer picks and a status that changes by itself. Both look like "an object holding an interface", so it is easy to mix the two patterns up.
Same class diagram, different intent
A context is the class that keeps a field of an interface type and delegates to it, meaning it passes each call on to the object in that field. Checkout and Order are contexts.
Checkout holds a PaymentMethod; Order holds an OrderState. The code below shows the same shape twice: an interface in a field, and calls passed on to it.
Example 1 · The same shape in both patterns
import java.math.BigDecimal;
// Strategy: HOW to do one job (take a payment)interface PaymentMethod { String pay(BigDecimal amount);}
class UpiPayment implements PaymentMethod { public String pay(BigDecimal amount) { return "UPI collect Rs. " + amount; }}
class Checkout { private PaymentMethod method;
void setPaymentMethod(PaymentMethod method) { this.method = method; }
String pay(BigDecimal amount) { return method.pay(amount); }}
// State: WHAT the object can do now (depends on its status)interface OrderState { String describe();}
class PlacedState implements OrderState { public String describe() { return "Placed: waiting for payment"; }}
class Order { private OrderState state = new PlacedState();
String describe() { return state.describe(); }}
public class SameShapeDemo { public static void main(String[] args) { Checkout checkout = new Checkout(); checkout.setPaymentMethod(new UpiPayment()); System.out.println("Strategy -> " + checkout.pay(new BigDecimal("899.00")));
Order order = new Order(); System.out.println("State -> " + order.describe()); }}Strategy -> UPI collect Rs. 899.00 State -> Placed: waiting for payment
What this code does
CheckoutandOrderare both contexts: each holds an interface field and delegates one call to it.- The code shape is identical; only the meaning differs: a way to pay versus the order's current situation.
Drawn as boxes and arrows, the two are identical. The difference is intent.
Strategy is about interchangeable ways to do one job: UPI, card or wallet all take a payment. State is about an object whose allowed actions change with its status: a placed order can be paid, a shipped one cannot be cancelled.
Who chooses: the client or the object itself
A transition is a move from one state to the next, such as PLACED to PAID. In the State pattern, each state decides which transitions it allows.
In Strategy, the client picks the object. In State, the object moves itself. The code below runs both: a customer who changes payment method, and an order that is paid twice.
Example 2 · The client chooses the strategy; the state chooses the next state
import java.math.BigDecimal;
interface PaymentMethod { String pay(BigDecimal amount);}
class UpiPayment implements PaymentMethod { public String pay(BigDecimal amount) { return "UPI Rs. " + amount; }}
class CardPayment implements PaymentMethod { public String pay(BigDecimal amount) { return "Card Rs. " + amount; }}
class Checkout { private PaymentMethod method;
void choose(PaymentMethod method) { this.method = method; } // the CLIENT chooses String pay(BigDecimal amount) { return method.pay(amount); }}
interface OrderState { OrderState pay(Order order); String name();}
class Placed implements OrderState { public OrderState pay(Order order) { return new Paid(); } // the STATE chooses the next state public String name() { return "PLACED"; }}
class Paid implements OrderState { public OrderState pay(Order order) { throw new IllegalStateException("Order is already paid"); } public String name() { return "PAID"; }}
class Order { private OrderState state = new Placed();
void pay() { state = state.pay(this); } String status() { return state.name(); }}
public class WhoChoosesDemo { public static void main(String[] args) { Checkout checkout = new Checkout(); checkout.choose(new UpiPayment()); System.out.println("Customer picked: " + checkout.pay(new BigDecimal("499.00"))); checkout.choose(new CardPayment()); System.out.println("Customer changed mind: " + checkout.pay(new BigDecimal("499.00")));
Order order = new Order(); System.out.println("Order status: " + order.status()); order.pay(); System.out.println("After pay(): " + order.status()); try { order.pay(); } catch (IllegalStateException e) { System.out.println("Second pay(): " + e.getMessage()); } }}Customer picked: UPI Rs. 499.00 Customer changed mind: Card Rs. 499.00 Order status: PLACED After pay(): PAID Second pay(): Order is already paid
What this code does
- The customer swaps the payment method freely with
choose. Nothing stops UPI being followed by card. order.pay()asks the current state for the next one. The order moved itself to PAID, and the PAID state refuses a second payment.
In Strategy, the client chooses. The customer, a setting or the caller code picks the payment method and passes it in, and can swap it at any time. The context never changes its own strategy.
In State, the object changes itself. Calling order.pay() makes the current state return the next state, and the order switches to it. Outside code asks for actions (pay, ship, cancel), never for a particular state class.
Predict the output
Who chooses?
Read each snippet and pick what happens.
Round 1 of 2
What does the last line print?
Do implementations know about each other?
An illegal transition is a move the state diagram does not allow, such as cancelling a shipped order. In the State pattern the state class rejects it, usually by throwing an exception.
Strategies never mention each other, but states name their neighbours. The code below shows three discount rules, then the paid, shipped and cancelled states.
Example 3 · Independent strategies, connected states
import java.util.List;
// Strategies: independent, none mentions anotherinterface DiscountRule { int apply(int total);}
class NoDiscount implements DiscountRule { public int apply(int total) { return total; }}
class FestivalDiscount implements DiscountRule { public int apply(int total) { return total - total / 10; }}
class StudentDiscount implements DiscountRule { public int apply(int total) { return Math.max(0, total - 100); }}
// States: each one knows which states can come nextinterface OrderState { OrderState ship(); OrderState cancel(); String name();}
class PaidState implements OrderState { public OrderState ship() { return new ShippedState(); } public OrderState cancel() { return new CancelledState(); } public String name() { return "PAID"; }}
class ShippedState implements OrderState { public OrderState ship() { throw new IllegalStateException("already shipped"); } public OrderState cancel() { throw new IllegalStateException("cannot cancel a shipped order"); } public String name() { return "SHIPPED"; }}
class CancelledState implements OrderState { public OrderState ship() { throw new IllegalStateException("cannot ship a cancelled order"); } public OrderState cancel() { throw new IllegalStateException("already cancelled"); } public String name() { return "CANCELLED"; }}
public class KnowEachOtherDemo { public static void main(String[] args) { for (DiscountRule rule : List.of(new NoDiscount(), new FestivalDiscount(), new StudentDiscount())) { System.out.println(rule.getClass().getSimpleName() + " on Rs. 1200: Rs. " + rule.apply(1200)); }
OrderState s = new PaidState(); s = s.ship(); System.out.println("State now: " + s.name()); try { s = s.cancel(); } catch (IllegalStateException e) { System.out.println("cancel() rejected: " + e.getMessage()); } }}NoDiscount on Rs. 1200: Rs. 1200 FestivalDiscount on Rs. 1200: Rs. 1080 StudentDiscount on Rs. 1200: Rs. 1100 State now: SHIPPED cancel() rejected: cannot cancel a shipped order
What this code does
- The three discount rules never mention each other, so any one can be removed safely.
PaidStatecreatesShippedState, andShippedStaterefusescancel(): the transitions are written inside the states.
Strategies are independent. FestivalDiscount never mentions StudentDiscount, so you can add or delete one without touching the others.
States know their neighbours. PaidState.ship() returns a ShippedState, and ShippedState.cancel() refuses. The rules of the state diagram live inside the state classes, which is what stops illegal moves such as cancelling a shipped order.
Find the bug
Break the pattern rule
Click the line that breaks the pattern.
A shipped order must not be cancellable. Which line allows it?
Round 1 of 2Side by side: payment strategy and order state
ShopLite uses both. The customer picks a PaymentMethod (Strategy) and passes it to order.pay(method); the order's own OrderState decides whether paying is allowed now.
Example 4 · A payment strategy inside an order state machine
import java.math.BigDecimal;
// ---- Strategy: how the customer pays ----interface PaymentMethod { String pay(BigDecimal amount);}
class UpiPayment implements PaymentMethod { public String pay(BigDecimal amount) { return "UPI Rs. " + amount; }}
class WalletPayment implements PaymentMethod { public String pay(BigDecimal amount) { return "Wallet Rs. " + amount; }}
// ---- State: what the order may do next ----interface OrderState { default OrderState pay(Order o, PaymentMethod m) { throw reject("pay"); } default OrderState ship(Order o) { throw reject("ship"); } default OrderState cancel(Order o) { throw reject("cancel"); } String name();
private IllegalStateException reject(String action) { return new IllegalStateException("cannot " + action + " when " + name()); }}
class Placed implements OrderState { public OrderState pay(Order o, PaymentMethod m) { System.out.println(" " + o.id() + " paid by " + m.pay(o.total())); return new Paid(); } public OrderState cancel(Order o) { return new Cancelled(); } public String name() { return "PLACED"; }}
class Paid implements OrderState { public OrderState ship(Order o) { return new Shipped(); } public OrderState cancel(Order o) { System.out.println(" refund Rs. " + o.total() + " for " + o.id()); return new Cancelled(); } public String name() { return "PAID"; }}
class Shipped implements OrderState { public String name() { return "SHIPPED"; }}
class Cancelled implements OrderState { public String name() { return "CANCELLED"; }}
class Order { private final String id; private final BigDecimal total; private OrderState state = new Placed();
Order(String id, BigDecimal total) { this.id = id; this.total = total; }
String id() { return id; } BigDecimal total() { return total; }
void pay(PaymentMethod method) { move(state.pay(this, method)); } void ship() { move(state.ship(this)); } void cancel() { move(state.cancel(this)); }
private void move(OrderState next) { System.out.println(id + ": " + state.name() + " -> " + next.name()); state = next; }}
public class SideBySideDemo { static void attempt(String label, Runnable action) { try { action.run(); } catch (IllegalStateException e) { System.out.println(label + " rejected: " + e.getMessage()); } }
public static void main(String[] args) { Order first = new Order("ORD-1", new BigDecimal("1499.00")); first.pay(new UpiPayment()); first.ship(); attempt("ORD-1 cancel", first::cancel);
Order second = new Order("ORD-2", new BigDecimal("299.00")); second.pay(new WalletPayment()); second.cancel(); attempt("ORD-2 ship", second::ship); }}ORD-1 paid by UPI Rs. 1499.00 ORD-1: PLACED -> PAID ORD-1: PAID -> SHIPPED ORD-1 cancel rejected: cannot cancel when SHIPPED ORD-2 paid by Wallet Rs. 299.00 ORD-2: PLACED -> PAID refund Rs. 299.00 for ORD-2 ORD-2: PAID -> CANCELLED ORD-2 ship rejected: cannot ship when CANCELLED
What this code does
pay(method)passes the customer's strategy to the current state, which uses it and returns the next state.- Default methods in
OrderStatereject every action, so each state overrides only what it allows; cancel after shipping and ship after cancelling are refused.
The split keeps each concern in one place: adding a wallet means one new payment class, and adding a "returned" status means one new state class plus the transitions into it.
Choosing between them
Ask two questions. Is this a family of ways to do the same job that a caller picks? Then Strategy. Does the object behave differently by status and move between statuses on its own? Then State.
- Discount type, sort order, shipping cost rule, file export format → Strategy.
- Order lifecycle, train ticket (waitlisted, confirmed, cancelled), seat hold, vending machine → State.
- Only a few statuses with simple rules → an enum with an allowed-transitions map can replace State classes.
Predict the output
Strategy or State?
Pick the pattern that fits each ShopLite need.
Round 1 of 3
Which pattern is this?
Next step
Check your understanding
12 quick questions