Skip to lesson

Behavioural patterns practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Six patterns, six kinds of problem. Which one fits a ShopLite scenario, and which slips break them most often? Try this optional checkpoint when you want to check yourself.

Choosing a behavioural pattern

Ask what changes or what must be decoupled, then match it to a pattern. Below, Strategy and State are compared in one program.

Example 1 · Strategy vs State in one program

StrategyVsStateDemo.javaJava
import java.util.Map;
interface DeliveryStrategy {    int cost(int amount);}
enum Status { PLACED, PAID, SHIPPED }               // State: the order moves itself
class Order {    private Status status = Status.PLACED;    private DeliveryStrategy delivery = amount -> amount >= 499 ? 0 : 40;
    void chooseDelivery(DeliveryStrategy delivery) {   // decided by the shopper        this.delivery = delivery;    }
    void advance() {                                 // decided by the order's own rules        status = switch (status) {            case PLACED -> Status.PAID;            case PAID, SHIPPED -> Status.SHIPPED;        };    }
    String summary(int amount) {        return status + ", delivery Rs " + delivery.cost(amount);    }}
public class StrategyVsStateDemo {    public static void main(String[] args) {        Map<String, DeliveryStrategy> options = Map.of("express", amount -> 99, "pickup", amount -> 0);        Order order = new Order();        System.out.println(order.summary(350));        order.chooseDelivery(options.get("express"));        order.advance();        System.out.println(order.summary(350));        order.advance();        System.out.println(order.summary(350));    }}
Output
PLACED, delivery Rs 40
PAID, delivery Rs 99
SHIPPED, delivery Rs 99

What this code does

  • The delivery rule changes only because the shopper chose express: that is Strategy. The status changes because the order follows its lifecycle: that is State.
  • A small lifecycle like this fits an enum; when each status gains its own behaviour, it grows into state classes.

Strategy and State look alike in code, so ask one more question: who changes the object? With Strategy the caller picks; with State the object moves itself through its lifecycle.

Match the problem to the pattern:

Mistake: a switch where a map of lambdas fits

A switch on a coupon code grows with every new rule, and the same switch often appears in several places. Below, it is replaced by a map of lambdas.

Example 2 · A discount switch and the same rules as a map of lambdas

SwitchToLambdasDemo.javaJava
import java.util.Map;import java.util.function.IntUnaryOperator;
public class SwitchToLambdasDemo {    static int withSwitch(String code, int amount) {        switch (code) {            case "FEST10": return amount * 10 / 100;            case "FLAT200": return amount >= 999 ? 200 : 0;            case "STUDENT": return Math.min(amount * 15 / 100, 300);            default: return 0;        }    }
    static final Map<String, IntUnaryOperator> RULES = Map.of(            "FEST10", amount -> amount * 10 / 100,            "FLAT200", amount -> amount >= 999 ? 200 : 0,            "STUDENT", amount -> Math.min(amount * 15 / 100, 300));
    static int withMap(String code, int amount) {        return RULES.getOrDefault(code, a -> 0).applyAsInt(amount);    }
    public static void main(String[] args) {        for (String code : new String[] {"FEST10", "FLAT200", "STUDENT", "BOGUS"}) {            System.out.println(code + ": switch " + withSwitch(code, 2999) + ", map " + withMap(code, 2999));        }    }}
Output
FEST10: switch 299, map 299
FLAT200: switch 200, map 200
STUDENT: switch 300, map 300
BOGUS: switch 0, map 0

What this code does

  • Both versions give the same discounts. In the map version, a new coupon is one new entry, and the map can be shared by checkout, the cart preview and the admin page.
  • getOrDefault with a zero rule plays the part of the default branch.

When each rule is a small calculation, keep the rules in a Map<String, Strategy> of lambdas, with getOrDefault for unknown codes. Adding a rule becomes adding one entry. Review: Strategy with lambdas (opens in a new tab).

Mistake: an undo that forgot the old state

A command's undo() can only restore what execute() saved. Below, one undo guesses and one remembers.

Example 3 · An undo that guesses, and an undo that remembers

UndoStateDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
interface Command {    void execute();    void undo();}
class GuessingRemove implements Command {    private final Map<String, Integer> cart;    private final String sku;
    GuessingRemove(Map<String, Integer> cart, String sku) {        this.cart = cart;        this.sku = sku;    }
    public void execute() { cart.remove(sku); }    public void undo() { cart.put(sku, 1); }               // bug: how many were there?}
class RememberingRemove implements Command {    private final Map<String, Integer> cart;    private final String sku;    private Integer oldQty;
    RememberingRemove(Map<String, Integer> cart, String sku) {        this.cart = cart;        this.sku = sku;    }
    public void execute() { oldQty = cart.remove(sku); }  // save, then change    public void undo() { if (oldQty != null) cart.put(sku, oldQty); }}
public class UndoStateDemo {    static void run(Command command, Map<String, Integer> cart) {        command.execute();        command.undo();        System.out.println(cart);    }
    public static void main(String[] args) {        Map<String, Integer> cart1 = new LinkedHashMap<>(Map.of("PEN-02", 3));        run(new GuessingRemove(cart1, "PEN-02"), cart1);        Map<String, Integer> cart2 = new LinkedHashMap<>(Map.of("PEN-02", 3));        run(new RememberingRemove(cart2, "PEN-02"), cart2);    }}
Output
{PEN-02=1}
{PEN-02=3}

What this code does

  • Both commands remove the 3 pen sets. The guessing one can only put back 1, because it never looked at the quantity before removing it.
  • Map.remove returns the old value, so saving the old state costs one assignment.

A remove command that does not remember the removed quantity can only guess, so the cart ends up with the wrong number of items.

The rule: in execute(), read and store the old value first, then change it. In undo(), put back exactly what was stored. Review: Command (opens in a new tab).

Mistake: a chain that never reaches the last handler

Every handler that does not reject a request must call the next one. Below, one handler cuts the chain short.

Example 4 · A handler that cuts the chain short

BrokenChainDemo.javaJava
record Order(int qty, String pincode) {}
abstract class Check {    private Check next;    private final String name;
    Check(String name) { this.name = name; }
    Check then(Check next) {        this.next = next;        return next;    }
    String check(Order o) {        System.out.println("  " + name + " ran");        return verify(o);    }
    protected String passOn(Order o) { return next == null ? "OK" : next.check(o); }    protected abstract String verify(Order o);}
class QtyCheck extends Check {    QtyCheck() { super("qty"); }    protected String verify(Order o) { return o.qty() > 10 ? "too many" : passOn(o); }}
class BrokenStockCheck extends Check {    BrokenStockCheck() { super("stock"); }    protected String verify(Order o) { return o.qty() > 50 ? "out of stock" : "OK"; }   // bug}
class FixedStockCheck extends Check {    FixedStockCheck() { super("stock"); }    protected String verify(Order o) { return o.qty() > 50 ? "out of stock" : passOn(o); }}
class PincodeCheck extends Check {    PincodeCheck() { super("pincode"); }    protected String verify(Order o) { return o.pincode().matches("[1-9][0-9]{5}") ? passOn(o) : "bad pincode"; }}
public class BrokenChainDemo {    public static void main(String[] args) {        Order badPincode = new Order(2, "41100");
        Check broken = new QtyCheck();        broken.then(new BrokenStockCheck()).then(new PincodeCheck());        System.out.println("Broken chain: " + broken.check(badPincode));
        Check fixed = new QtyCheck();        fixed.then(new FixedStockCheck()).then(new PincodeCheck());        System.out.println("Fixed chain: " + fixed.check(badPincode));    }}
Output
  qty ran
  stock ran
Broken chain: OK
  qty ran
  stock ran
  pincode ran
Fixed chain: bad pincode

What this code does

  • The broken stock check returns "OK" itself, so the pincode check never runs and an order with a five-digit pincode is accepted.
  • Printing which handlers ran makes the problem visible, and testing with a request that should fail at the last handler catches it.

A handler that returns its own "OK" ends the chain early, so the handlers after it silently never run. The order passes validation, but the address was never checked.

Test a chain with a request that should fail at the last handler. If it passes, a handler in the middle is not passing requests on. Review: Chain of Responsibility (opens in a new tab).

Finish up

Mark complete & continue

Next: Project: ShopLite order lifecycle