Java Strategy and State Patterns: Swap Behavior at Runtime
Maya's bookstore sells online now, and the checkout takes three kinds of payment — card, wallet, and cash on delivery. A fourth is coming: gift cards, for the holidays. Every new method means the same edit: another branch in the checkout's if-chain, another round of re-testing what already works. And the orders themselves are tracked with a status flag — a string that says NEW or PAID or SHIPPED — checked by an if-chain in every method. The checkout knows every payment method by name, and the order's life is a string anyone can rewrite. That is the problem.
Post 1 asked what varies? Post 2, Java Singleton Pattern: Enum, Lazy Holder & Double-Checked Locking Explained, asked how many? Post 3, Java Factory Pattern: Factory Method vs Abstract Factory With Examples, asked who decides which object gets created? Post 4, Java Builder Pattern: Build Complex Objects Without Telescoping Constructors, asked how do you assemble one object, piece by piece? Post 5, Java Adapter and Facade Patterns: Integrate Incompatible Code Cleanly, asked how do you use an interface you cannot change? Post 6, Java Decorator and Proxy Patterns: Add Behavior Without Changing Classes, asked how do you add behavior without changing a class? Post 7, Java Observer Pattern: Events, Listeners and Reactive Design Explained, asked how do many things learn about one change? This post asks an eighth question: how does one checkout take any payment method, and how does an order know what it may do next? The answer is two patterns with one shape: Strategy and State. The principle for this lesson: If a chain of ifs chooses behavior, the behavior deserves its own type.
1. The customer problem
Maya's requirement is plain: adding a payment method must not mean editing the checkout, and an order must refuse — loudly — to do what its life does not allow. A fourth method is coming, and the checkout must take it without a single changed line. An unpaid order must never ship, and a delivered order must never go back. One checkout, any payment method. One order, one life, enforced by the code.
She asked for two properties: the checkout must not name its payment methods, and the order must not carry its life as a flag. The test is simple: add a fourth payment method without touching the checkout, try to ship an order that was never paid, and cancel an order that already shipped — the first must work, and the other two must fail loudly.
2. Clarify the ask: what varies, what stays
Before writing any code, split the problem again:
- What stays stable: the checkout's job — take an amount, charge it — and the order's life — NEW, PAID, SHIPPED, DELIVERED, in that order. The steps will not change.
- What varies: which payment method charges the amount, and which step the order is on — and what that step allows. The method varies; the charging does not. The state varies; the life does not.
Section 5 shows what happens without that split: the checkout switching on a method string — each new method an edit to the checkout, each typo a silent fall-through — and the order's life as a string flag, which any method can rewrite to anything.
3. The minimum concept: two patterns, one shape
Strategy and State answer two questions with one shape: what if the behavior were an object? Two patterns, each with one job:
- The strategy interface —
PaymentStrategy: one method,pay, that every payment method implements. - The concrete strategies —
CardPayment,WalletPayment,CashPayment: each one charges the amount its own way. - The context —
Checkout: it holds a strategy and callspay, and never names a method. - The client — the code that chooses a strategy, which picks one and hands it to the checkout.
And the second pattern, the same shape turned inward:
- The state interface —
OrderState: one method per action —pay,ship,deliver,cancel— that every state implements. - The concrete states —
NewState,PaidState,ShippedState,DeliveredState, andCancelledState: each one decides what is legal from here. - The context —
Order: it holds a state and delegates every action to it, and never holds a status flag.
The difference between the two is worth naming precisely. A strategy answers a question the client asks: which algorithm, this time? The client chooses, and the checkout uses it. A state answers a question the object asks itself: what am I allowed to do now? The order does not choose its state — the state decides, and the order follows. Same shape, different question. And the difference from post 7 is worth naming too: an observer announces one change to many listeners; a strategy swaps one behavior at runtime; a state lets one object change what it does as its life advances. Post 9 turns requests and algorithms into objects of their own.
4. Build: one checkout, three methods, one life
Start with what stays stable — the strategy interface. One method: charge this amount, however this method charges.
// One method: charge this amount, however this method charges.
interface PaymentStrategy {
void pay(double amount);
} The three strategies, each with one job — and each remembering what it charged, so section 6 can prove the payment happened:
// Charges a card, and remembers what it charged.
final class CardPayment implements PaymentStrategy {
private double charged;
public void pay(double amount) {
charged = amount;
System.out.println("card: charged " + amount);
}
double charged() {
return charged;
}
}
// Charges a wallet, and remembers what it charged.
final class WalletPayment implements PaymentStrategy {
private double charged;
public void pay(double amount) {
charged = amount;
System.out.println("wallet: charged " + amount);
}
double charged() {
return charged;
}
}
// Collects cash on delivery, and remembers the amount to collect.
final class CashPayment implements PaymentStrategy {
private double charged;
public void pay(double amount) {
charged = amount;
System.out.println("cash: collect " + amount + " on delivery");
}
double charged() {
return charged;
}
} Now the checkout. It holds a strategy, it never names a method, and the strategy can be swapped while the checkout is running — that swap is the whole point:
// The checkout: it takes a payment strategy and never names a method.
final class Checkout {
private PaymentStrategy strategy;
Checkout(PaymentStrategy strategy) {
this.strategy = strategy;
}
void setStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
void pay(double amount) {
strategy.pay(amount);
}
} The second half: the order's life as objects. One method per action — each state decides what is legal from here:
// One method per action: each state decides what is legal from here.
interface OrderState {
void pay(Order order);
void ship(Order order);
void deliver(Order order);
void cancel(Order order);
String name();
} The first two states — every illegal move throws, with the rule named in the message:
// NEW: the order can be paid or cancelled, and nothing else.
final class NewState implements OrderState {
public void pay(Order order) {
order.setState(new PaidState());
System.out.println("order " + order.id() + ": NEW -> PAID");
}
public void ship(Order order) {
throw new IllegalStateException("cannot ship a NEW order");
}
public void deliver(Order order) {
throw new IllegalStateException("cannot deliver a NEW order");
}
public void cancel(Order order) {
order.setState(new CancelledState());
System.out.println("order " + order.id() + ": NEW -> CANCELLED");
}
public String name() {
return "NEW";
}
}
// PAID: the order can be shipped or cancelled, and nothing else.
final class PaidState implements OrderState {
public void pay(Order order) {
throw new IllegalStateException("cannot pay a PAID order");
}
public void ship(Order order) {
order.setState(new ShippedState());
System.out.println("order " + order.id() + ": PAID -> SHIPPED");
}
public void deliver(Order order) {
throw new IllegalStateException("cannot deliver a PAID order");
}
public void cancel(Order order) {
order.setState(new CancelledState());
System.out.println("order " + order.id() + ": PAID -> CANCELLED");
}
public String name() {
return "PAID";
}
} The remaining three follow the same shape — a shipped order can only be delivered, and delivered and cancelled orders are terminal:
// SHIPPED: the order can only be delivered.
final class ShippedState implements OrderState {
public void pay(Order order) {
throw new IllegalStateException("cannot pay a SHIPPED order");
}
public void ship(Order order) {
throw new IllegalStateException("cannot ship a SHIPPED order");
}
public void deliver(Order order) {
order.setState(new DeliveredState());
System.out.println("order " + order.id() + ": SHIPPED -> DELIVERED");
}
public void cancel(Order order) {
throw new IllegalStateException("cannot cancel a SHIPPED order");
}
public String name() {
return "SHIPPED";
}
}
// DELIVERED: terminal — every action throws.
final class DeliveredState implements OrderState {
public void pay(Order order) {
throw new IllegalStateException("cannot pay a DELIVERED order");
}
public void ship(Order order) {
throw new IllegalStateException("cannot ship a DELIVERED order");
}
public void deliver(Order order) {
throw new IllegalStateException("cannot deliver a DELIVERED order");
}
public void cancel(Order order) {
throw new IllegalStateException("cannot cancel a DELIVERED order");
}
public String name() {
return "DELIVERED";
}
}
// CANCELLED: terminal — every action throws.
final class CancelledState implements OrderState {
public void pay(Order order) {
throw new IllegalStateException("cannot pay a CANCELLED order");
}
public void ship(Order order) {
throw new IllegalStateException("cannot ship a CANCELLED order");
}
public void deliver(Order order) {
throw new IllegalStateException("cannot deliver a CANCELLED order");
}
public void cancel(Order order) {
throw new IllegalStateException("cannot cancel a CANCELLED order");
}
public String name() {
return "CANCELLED";
}
} And the order itself — it delegates every action to its current state, and holds no status flag:
// The order: it delegates to its current state and holds no status flag.
final class Order {
private final int id;
private OrderState state = new NewState();
Order(int id) {
this.id = id;
}
void pay() {
state.pay(this);
}
void ship() {
state.ship(this);
}
void deliver() {
state.deliver(this);
}
void cancel() {
state.cancel(this);
}
void setState(OrderState state) {
this.state = state;
}
String stateName() {
return state.name();
}
int id() {
return id;
}
} The whole thing working, end to end — one checkout, three methods swapped at runtime, and one order walking its life:
public class ShopDemo {
public static void main(String[] args) {
Checkout checkout = new Checkout(new CardPayment());
checkout.pay(49.99);
checkout.setStrategy(new WalletPayment());
checkout.pay(49.99);
checkout.setStrategy(new CashPayment());
checkout.pay(49.99);
Order order = new Order(1024);
order.pay();
order.ship();
order.deliver();
}
} card: charged 49.99
wallet: charged 49.99
cash: collect 49.99 on delivery
order 1024: NEW -> PAID
order 1024: PAID -> SHIPPED
order 1024: SHIPPED -> DELIVERED Read that output out loud: the same checkout charged three ways without a single if, and the order moved NEW to PAID to SHIPPED to DELIVERED with no flag in sight. But the first version has three holes — and section 5 opens each one up.
5. Break it: the method that never charged, the order that shipped unpaid, and the checkout that failed too late
The first version works. Working is not the same as correct — and this version has three holes.
The first hole is the if-chain the strategy replaced. It matches strings, and strings have typos. A new method — or a misspelled one — falls through every branch, and nothing complains. Here is the old checkout, still in production:
// The old checkout: one method, one if-chain, and a silent fall-through.
final class OldCheckout {
void pay(String method, double amount) {
if ("card".equals(method)) {
System.out.println("card: charged " + amount);
} else if ("wallet".equals(method)) {
System.out.println("wallet: charged " + amount);
} else if ("cash".equals(method)) {
System.out.println("cash: collect " + amount + " on delivery");
}
System.out.println("order paid: " + amount);
}
} OldCheckout checkout = new OldCheckout();
checkout.pay("Card", 49.99); order paid: 49.99 Read that output again: one line, "order paid: 49.99" — and no charge line above it. The method was "Card" with a capital C, the chain only knows "card", and the order was marked paid with no money taken. The same fall-through waits for a genuinely new method: add "upi" tomorrow and the chain has no branch for it — same silence, same paid order, same missing money.
The second hole is the flag: a string accepts any value, and no method checks it. An order that was never paid ships without a word. Here is the old order:
// The old order: a status flag, and a ship method that trusts it.
final class OldOrder {
private String status = "NEW";
void ship() {
status = "SHIPPED";
System.out.println("order shipped");
}
String status() {
return status;
}
} OldOrder order = new OldOrder();
System.out.println("status before ship: " + order.status());
order.ship();
System.out.println("status after ship: " + order.status()); status before ship: NEW
order shipped
status after ship: SHIPPED The order went from NEW to SHIPPED without ever being PAID, and nothing objected — the flag cannot object, it is a string. The same hole runs the other way: one assignment, status = "NEW", and a delivered order is new again, its history erased by a line no reviewer would flag.
The third hole is the smallest, and the easiest to miss in review: a checkout built with no strategy at all. Nothing fails at construction — the failure waits until the customer is already paying:
Checkout checkout = new Checkout(null);
Order order = new Order(1025);
System.out.println("order " + order.id() + " created");
try {
checkout.pay(49.99);
} catch (NullPointerException e) {
System.out.println("caught: " + e);
}
System.out.println("order " + order.id() + " state: " + order.stateName()); order 1025 created
caught: java.lang.NullPointerException
order 1025 state: NEW The order was created, the customer was already paying, and only then did the checkout discover it had no way to charge — a NullPointerException with no message, at the worst possible moment. A failure that could have been caught when the checkout was built arrived when the money was due.
6. Harden it: fail fast, let the state decide, prove the extension
The fix shape is the same every time: the implied rule, now written where the code can enforce it. Two of the three breaks are fixed by the patterns themselves — the strategy ends the if-chain, the state ends the flag — and the third needs one more line.
First, the null check. Only the constructor and the setter change; the rest of Checkout stays as section 4 wrote it. One import joins it:
// One new import:
import java.util.Objects;
// The only change to Checkout: fail fast, at construction, not at pay time.
Checkout(PaymentStrategy strategy) {
this.strategy = Objects.requireNonNull(strategy, "payment strategy is required");
}
void setStrategy(PaymentStrategy strategy) {
this.strategy = Objects.requireNonNull(strategy, "payment strategy is required");
} requireNonNull throws a NullPointerException with the message "payment strategy is required" — at construction, before any order exists. The setter gets the same check, so a strategy can never be swapped for nothing at runtime either. Section 5's checkout failed when the money was due; this one fails when it is built, when the fix is one line and nobody is waiting.
Second, the states. The build version already throws on illegal transitions — that is the pattern doing its job — but notice what the throw carries: the exact rule, in words. "cannot ship a NEW order" names the action and the state, so the error message is the rulebook, not a riddle. Each order gets fresh state objects — a state belongs to its order, and no two orders share one. The states hold no data, so one shared instance per state would also be safe; fresh objects keep the ownership visible, and they cost nothing.
Third, the proof that the seam works: a fourth payment method, written after the checkout was finished, without touching it:
// A fourth payment method, added after the checkout was written.
final class GiftCardPayment implements PaymentStrategy {
private double charged;
public void pay(double amount) {
charged = amount;
System.out.println("gift card: charged " + amount);
}
double charged() {
return charged;
}
} Verify with explicit checks, not assertions — the same discipline as posts 1, 3, 4, 5, 6, and 7. Assertions can be switched off at runtime. The check program throws on mismatch — and its twelve checks prove the checkout swaps methods, the null fails fast, the order walks its life, the illegal moves throw with the rule named, and the fourth method needs no change to Checkout:
public class StrategyStateDemo {
public static void main(String[] args) {
// 1. One checkout, three strategies, swapped at runtime.
CardPayment card = new CardPayment();
WalletPayment wallet = new WalletPayment();
CashPayment cash = new CashPayment();
Checkout checkout = new Checkout(card);
checkout.pay(49.99);
check("card charges", card.charged() == 49.99);
checkout.setStrategy(wallet);
checkout.pay(49.99);
check("wallet charges after a swap", wallet.charged() == 49.99);
checkout.setStrategy(cash);
checkout.pay(49.99);
check("cash records the amount", cash.charged() == 49.99);
// 2. A null strategy fails fast, at construction.
try {
new Checkout(null);
check("null strategy fails at construction", false);
} catch (NullPointerException e) {
check("null strategy fails at construction", "payment strategy is required".equals(e.getMessage()));
}
// 3. The order walks its life, one legal step at a time.
Order order = new Order(1024);
order.pay();
check("pay moves NEW to PAID", "PAID".equals(order.stateName()));
order.ship();
check("ship moves PAID to SHIPPED", "SHIPPED".equals(order.stateName()));
order.deliver();
check("deliver moves SHIPPED to DELIVERED", "DELIVERED".equals(order.stateName()));
// 4. Illegal transitions throw, with the exact rule named.
Order unpaid = new Order(1025);
try {
unpaid.ship();
check("ship from NEW is refused", false);
} catch (IllegalStateException e) {
System.out.println("caught: " + e.getMessage());
check("ship from NEW is refused", "cannot ship a NEW order".equals(e.getMessage()));
}
try {
order.pay();
check("pay on DELIVERED is refused", false);
} catch (IllegalStateException e) {
System.out.println("caught: " + e.getMessage());
check("pay on DELIVERED is refused", "cannot pay a DELIVERED order".equals(e.getMessage()));
}
// 5. Cancel is a state too, and it is terminal.
Order cancelled = new Order(1026);
cancelled.pay();
cancelled.cancel();
check("cancel moves PAID to CANCELLED", "CANCELLED".equals(cancelled.stateName()));
try {
cancelled.deliver();
check("deliver on CANCELLED is refused", false);
} catch (IllegalStateException e) {
System.out.println("caught: " + e.getMessage());
check("deliver on CANCELLED is refused", "cannot deliver a CANCELLED order".equals(e.getMessage()));
}
// 6. A fourth strategy needs no change to Checkout.
GiftCardPayment gift = new GiftCardPayment();
checkout.setStrategy(gift);
checkout.pay(25.00);
check("gift card needs no Checkout change", gift.charged() == 25.00);
}
static void check(String name, boolean condition) {
if (!condition) {
throw new IllegalStateException("FAILED: " + name);
}
System.out.println("ok: " + name);
}
} card: charged 49.99
ok: card charges
wallet: charged 49.99
ok: wallet charges after a swap
cash: collect 49.99 on delivery
ok: cash records the amount
ok: null strategy fails at construction
order 1024: NEW -> PAID
ok: pay moves NEW to PAID
order 1024: PAID -> SHIPPED
ok: ship moves PAID to SHIPPED
order 1024: SHIPPED -> DELIVERED
ok: deliver moves SHIPPED to DELIVERED
caught: cannot ship a NEW order
ok: ship from NEW is refused
caught: cannot pay a DELIVERED order
ok: pay on DELIVERED is refused
order 1026: NEW -> PAID
order 1026: PAID -> CANCELLED
ok: cancel moves PAID to CANCELLED
caught: cannot deliver a CANCELLED order
ok: deliver on CANCELLED is refused
gift card: charged 25.0
ok: gift card needs no Checkout change When not to use a strategy or a state. A strategy is a seam for behavior that varies — and sometimes it does not vary. As a rule of thumb — not a law — one payment method that will never change is an if, not an interface; two steps that never grow are a flag, not five classes. The patterns earn their keep when the set is open-ended: a fourth method arriving, a life with rules worth enforcing.
Next step, not this post: an order that announces its changes. The state pattern decides what is legal; post 7's Observer announces that something happened. Put them together and the order can tell the display, the log, and the shipping desk every time it moves — NEW to PAID, PAID to SHIPPED — without knowing any of them. This post's order is silent; the combination is where to look when the rest of the shop needs to hear about it.
7. Communicate: explain it to a human
The code is only half the job. Here is how you explain this change to Maya, without jargon:
"Before, the checkout knew every payment method by name — card, wallet, cash — and every new method meant opening the checkout and adding a branch, then re-testing all of it. Now the checkout just says: charge this amount, however you charge. Each method is its own small piece, and a new one plugs in without anyone touching the checkout. And the order no longer carries its life as a word anyone can rewrite — it moves from new to paid to shipped to delivered, one legal step at a time, and a step that breaks the rules is refused out loud instead of failing quietly. The one trade-off: there are more pieces than before — a class per method, a class per state — and each one has to earn its place."
If she understands that paragraph, she understands the design — and she can approve the next change with confidence, because she knows what "any method, one checkout" guarantees and what it costs.
Field check
Six rules to carry into the rest of the track:
- If an if-chain chooses behavior, give the behavior a type. A chain that grows with every new variant is a strategy waiting to be named.
- A state is an object, not a flag. If a string can hold a value the life does not allow, the life is not enforced.
- Illegal moves must throw, and the message must name the rule. A silent no is a bug the next reader will not find.
- Fail fast at construction. A checkout with no strategy must fail when it is built, not when the money is due.
- A new variant is a new class, and nothing else changes. If adding a payment method edits the checkout, the seam is not a seam.
- No strategy without more than one behavior, no state without more than one step. One method is an if; one step is a flag. A pattern is a tool, not a goal.
Previous in this track: Java Observer Pattern: Events, Listeners and Reactive Design Explained · Continue: Java Learning Roadmap 2026
Comments
Post a Comment