JAVA-270 · Lesson 5 of 12 · 25 min
Behavioral patterns
▶ Video coming soon A video version of this lesson is on the way.
Tuesday, February 8, 2028. Tamsin has been grumbling about the repair queue screen in CounterApp. It sorts tickets one fixed way, by number, when on busy days she wants rental damage first and on quiet days she wants the oldest tickets first. Nobody is told when a part runs low until somebody opens the stock screen. And when a volunteer types the wrong count into a stock adjustment, there is no way to undo it. Ingrid says all three complaints have well-known answers in the third group of Gang of Four patterns, the behavioral ones, and that modern Java makes most of them much shorter than the 1994 book's versions.
What behavioral patterns do
Behavioral patterns are about how objects share responsibilities and communicate: who decides, who is told, and how a request travels from the code that makes it to the code that carries it out. Many of them have the same basic move. A piece of behavior that would otherwise be hard-coded in a method, such as a sorting rule or an action to perform, becomes an object that can be passed around, stored, swapped or undone.
In 1994 that meant writing a small interface and one class per behavior. Since Java 8, a functional interface, an interface with a single abstract method, can be implemented with a lambda or a method reference, so a behavior object often takes one line. Records and sealed types, added in Java 16 and 17, make other patterns shorter still. This lesson shows each pattern in its modern form and explains what problem it solves.
Strategy
The strategy pattern defines a family of interchangeable algorithms, puts each one behind the same interface, and lets the client choose one at run time. The code that uses the algorithm does not change when a new one is added. Java's own library is full of strategies: a Comparator is a sorting strategy, and passing a different one to sort changes the order without changing the sort.
import java.util.*;
public class Main {
enum Urgency { RENTAL_DAMAGE, NEEDED_TOMORROW, ROUTINE }
record Ticket(int number, String kind, Urgency urgency, int dayIn) {}
static final Map<String, Comparator<Ticket>> STRATEGIES = new LinkedHashMap<>();
static {
STRATEGIES.put("by number", Comparator.comparingInt(Ticket::number));
STRATEGIES.put("busy day", Comparator.comparing(Ticket::urgency).thenComparingInt(Ticket::dayIn));
STRATEGIES.put("quiet day", Comparator.comparingInt(Ticket::dayIn).thenComparingInt(Ticket::number));
}
public static void main(String[] args) {
List<Ticket> queue = List.of(new Ticket(701, "FLAT", Urgency.ROUTINE, 3),
new Ticket(702, "BRAKES", Urgency.RENTAL_DAMAGE, 5),
new Ticket(703, "GEARS", Urgency.NEEDED_TOMORROW, 1),
new Ticket(704, "TUNE_UP", Urgency.ROUTINE, 1));
for (var s : STRATEGIES.entrySet()) {
List<Ticket> sorted = new ArrayList<>(queue);
sorted.sort(s.getValue());
System.out.println(s.getKey() + ": " + sorted.stream().map(t -> t.number() + " " + t.kind()).toList());
}
}
}by number: [701 FLAT, 702 BRAKES, 703 GEARS, 704 TUNE_UP] busy day: [702 BRAKES, 703 GEARS, 704 TUNE_UP, 701 FLAT] quiet day: [703 GEARS, 704 TUNE_UP, 701 FLAT, 702 BRAKES]
What this code does
Each ordering Tamsin wants is a Comparator, which is a strategy for sorting, and the three strategies sit in a map under their names. The same sort call produces a different queue depending on which strategy is passed in. Adding a new ordering means adding one entry, with no change to the code that sorts and displays the queue.
Strategy replaces long if-else chains that pick an algorithm by a flag, which is the open/closed principle from lesson 2 in pattern form. Use it when there are several ways to do one job and the choice varies by situation, customer or configuration.
Observer
The observer pattern lets one object, the subject, notify any number of other objects, the observers, when something happens, without knowing what those observers are or what they do. Observers register with the subject; when the event occurs, the subject calls each one. The subject depends only on a small listener interface, so new reactions can be added without changing it.
import java.util.*;
import java.util.function.BiConsumer;
public class Main {
static final class Shelf {
private final Map<String, Integer> counts = new TreeMap<>(Map.of("TUBE-700x25", 6, "BELL", 2));
private final Map<String, Integer> minimum = Map.of("TUBE-700x25", 5, "BELL", 1);
private final List<BiConsumer<String, Integer>> lowStockListeners = new ArrayList<>();
void onLowStock(BiConsumer<String, Integer> listener) { lowStockListeners.add(listener); }
void take(String code, int n) {
int left = counts.merge(code, -n, Integer::sum);
if (left < minimum.get(code)) for (var l : lowStockListeners) l.accept(code, left);
}
}
public static void main(String[] args) {
Shelf shelf = new Shelf();
List<String> reorderList = new ArrayList<>();
shelf.onLowStock((code, left) -> System.out.println("screen: " + code + " is low (" + left + " left)"));
shelf.onLowStock((code, left) -> reorderList.add(code));
shelf.take("TUBE-700x25", 1);
shelf.take("TUBE-700x25", 1);
shelf.take("BELL", 2);
System.out.println("reorder list: " + reorderList);
}
}screen: TUBE-700x25 is low (4 left) screen: BELL is low (0 left) reorder list: [TUBE-700x25, BELL]
What this code does
Shelf is the subject: it keeps a list of listeners and calls each one when a count drops below its minimum. Two observers register with lambdas, one that shows a message on the counter screen and one that adds the part to Kofi's reorder list, and Shelf knows nothing about either. The first sale leaves 5 tubes, which is not below the minimum, so the screen speaks only after the second.
Observers are everywhere: button clicks in user interfaces, events in web frameworks, messages between services. Two cautions apply. Observers are called in the subject's thread and in the order they registered, so a slow observer slows the subject down. And observers that are never removed keep their objects alive, a common source of memory leaks in long-running programs.
Command
The command pattern turns a request into an object. Instead of calling a method directly, you create an object that represents the action, with everything needed to carry it out. Because the action is now data, it can be queued, logged, sent elsewhere, retried or, most usefully at the counter, undone.
Kofi's wish for undo is a classic command problem. Each stock adjustment becomes a record that knows how to apply itself and how to reverse itself, and the program keeps a stack of the ones it has applied.
import java.util.*;
public class Main {
static final Map<String, Integer> stock = new TreeMap<>(Map.of("BELL", 3, "CHAIN-11", 2));
sealed interface Command permits Receive, Sell {
void apply();
void undo();
}
record Receive(String code, int n) implements Command {
public void apply() { stock.merge(code, n, Integer::sum); }
public void undo() { stock.merge(code, -n, Integer::sum); }
}
record Sell(String code, int n) implements Command {
public void apply() { stock.merge(code, -n, Integer::sum); }
public void undo() { stock.merge(code, n, Integer::sum); }
}
public static void main(String[] args) {
Deque<Command> history = new ArrayDeque<>();
for (Command c : List.of(new Receive("BELL", 10), new Sell("CHAIN-11", 1), new Receive("BELL", 100))) {
c.apply();
history.push(c);
System.out.println("did " + c + " -> " + stock);
}
Command mistake = history.pop();
mistake.undo();
System.out.println("undid " + mistake + " -> " + stock);
System.out.println("history: " + history);
}
}did Receive[code=BELL, n=10] -> {BELL=13, CHAIN-11=2}
did Sell[code=CHAIN-11, n=1] -> {BELL=13, CHAIN-11=1}
did Receive[code=BELL, n=100] -> {BELL=113, CHAIN-11=1}
undid Receive[code=BELL, n=100] -> {BELL=13, CHAIN-11=1}
history: [Sell[code=CHAIN-11, n=1], Receive[code=BELL, n=10]]What this code does
Receive and Sell are commands: records that carry their part code and quantity and know how to apply and undo themselves. Every applied command is pushed onto a stack, so undoing the last one is a pop and a call to undo. The volunteer who typed 100 bells instead of 10 can reverse the mistake, and the remaining history is still there for an audit.
The same design gives an audit log for free: write each command to a file as it is applied, and the file is a complete record of what happened to the stock. Lambdas can also be commands, a Runnable is one, but a lambda cannot easily be undone or printed, which is why records are the better choice here.
Template method
The template method pattern defines the skeleton of an algorithm in a parent class, with the fixed steps written once, and leaves some steps to subclasses. Every report at Second Gear has the same shape: a title, a line for each item, and a footer with a total. Only the data and the line format differ.
import java.util.*;
public class Main {
static abstract class Report<T> {
final void print(List<T> items) {
System.out.println("== " + title() + " ==");
int total = 0;
for (T item : items) { System.out.println(line(item)); total += amount(item); }
System.out.println("total: " + total);
}
abstract String title();
abstract String line(T item);
abstract int amount(T item);
}
record Sale(String code, int cents) {}
record Repair(int ticket, int minutes) {}
static final class SalesReport extends Report<Sale> {
String title() { return "Parts sold"; }
String line(Sale s) { return s.code() + " " + s.cents(); }
int amount(Sale s) { return s.cents(); }
}
static final class WorkshopReport extends Report<Repair> {
String title() { return "Bench minutes"; }
String line(Repair r) { return "ticket " + r.ticket() + ": " + r.minutes() + " min"; }
int amount(Repair r) { return r.minutes(); }
}
public static void main(String[] args) {
new SalesReport().print(List.of(new Sale("BELL", 650), new Sale("TUBE-700x25", 899)));
new WorkshopReport().print(List.of(new Repair(701, 25), new Repair(702, 50)));
}
}== Parts sold == BELL 650 TUBE-700x25 899 total: 1549 == Bench minutes == ticket 701: 25 min ticket 702: 50 min total: 75
What this code does
Report.print is the template method: it fixes the order of the steps, title, lines and total, and is final so subclasses cannot change it. Each subclass fills in only the three steps that differ, so every report has the same shape and the totaling logic exists once. A new report means a new subclass with three small methods.
Template method uses inheritance, and lesson 6 explains why inheritance should be used with care. In modern Java the same result is often reached by passing the varying steps as functions to one method, for example print(items, title, lineFormatter, amountFunction), which avoids creating a subclass for each report. Both forms are common; the inheritance form is reasonable when the steps belong together and there are several of them.
State
The state pattern lets an object change its behavior when its internal state changes, by representing each state as its own type. Instead of a field holding a status code and every method checking it with if statements, the object delegates to its current state, and each state knows which actions it allows and which state comes next.
A repair ticket at Second Gear moves through a life cycle: received, waiting for parts, in progress, ready, collected. Some moves are not allowed, such as collecting a bike that is not ready. With sealed interfaces and records, each state can be a small type, and a switch over the sealed type lets the compiler check that every state is handled.
public class Main {
sealed interface Status permits Received, WaitingForParts, InProgress, Ready, Collected {}
record Received() implements Status {}
record WaitingForParts(String part) implements Status {}
record InProgress(String mechanic) implements Status {}
record Ready(int cents) implements Status {}
record Collected() implements Status {}
static Status next(Status s, String event) {
return switch (s) {
case Received r when event.equals("start") -> new InProgress("Tamsin");
case Received r when event.equals("part missing") -> new WaitingForParts("CHAIN-11");
case WaitingForParts w when event.equals("part arrived") -> new InProgress("Tamsin");
case InProgress i when event.equals("finish") -> new Ready(6500);
case Ready r when event.equals("pay") -> new Collected();
default -> throw new IllegalStateException(event + " is not allowed when " + s);
};
}
public static void main(String[] args) {
Status s = new Received();
for (String event : new String[] {"part missing", "part arrived", "finish", "collect early?", "pay"}) {
try {
s = next(s, event);
System.out.println(event + " -> " + s);
} catch (IllegalStateException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}
}part missing -> WaitingForParts[part=CHAIN-11] part arrived -> InProgress[mechanic=Tamsin] finish -> Ready[cents=6500] rejected: collect early? is not allowed when Ready[cents=6500] pay -> Collected[]
What this code does
Each state of a repair ticket is a record, and the sealed Status interface lists them all. The next method uses pattern matching with guards to say which event is allowed in which state and what the new state is; anything else throws. Because states are types, a Ready state can carry its price and a WaitingForParts state the missing part.
In the Gang of Four version, each state class has methods for every event, and the context object forwards calls to its current state. That form suits states with a lot of behavior each. The switch form above suits tickets, where the main question is which transitions are allowed. Both get rid of status codes checked in scattered if statements.
Iterator
The iterator pattern provides a way to visit the elements of a collection one at a time without exposing how the collection is stored. Java builds it into the language: any class that implements Iterable can be used in an enhanced for loop, and every standard collection does. You write your own when you have a collection-like object whose contents are computed or stored in an unusual way, such as the free repair slots in a day.
import java.util.*;
public class Main {
record Slot(int hour, int free) {}
static final class Day implements Iterable<Slot> {
private final int[] booked = new int[24];
Day book(int hour) { booked[hour]++; return this; }
public Iterator<Slot> iterator() {
return new Iterator<>() {
private int hour = 9;
public boolean hasNext() { return hour <= 15; }
public Slot next() {
if (!hasNext()) throw new NoSuchElementException();
Slot s = new Slot(hour, 2 - booked[hour]);
hour++;
return s;
}
};
}
}
public static void main(String[] args) {
Day saturday = new Day().book(10).book(10).book(13);
for (Slot s : saturday) {
if (s.free() > 0) System.out.println(s.hour() + ":00 has " + s.free() + " free");
}
}
}9:00 has 2 free 11:00 has 2 free 12:00 has 2 free 13:00 has 1 free 14:00 has 2 free 15:00 has 2 free
What this code does
Day stores bookings in an array of 24 counts, but callers never see the array. Its iterator walks the repair hours from 9:00 to 15:00 and produces a Slot for each, with two places per hour minus what is booked. Because Day implements Iterable, an ordinary for loop visits the slots, and the full 10:00 slot is simply skipped by the caller.
Streams are a second, more powerful form of iteration in modern Java, and lesson 9's domain model uses them. Write a custom Iterator only when the for-each form is what callers really need; otherwise returning a List or a Stream is simpler.
Choosing a behavioral pattern
| Problem | Pattern | Modern Java form |
|---|---|---|
| Several interchangeable ways to do one job | Strategy | A functional interface such as Comparator, passed in or chosen from a map |
| Others must react when something happens | Observer | A list of listener lambdas |
| Actions must be queued, logged or undone | Command | Records implementing a sealed command interface |
| Several algorithms share one fixed skeleton | Template method | An abstract class with a final method, or a method taking functions |
| Allowed actions depend on an object's status | State | A sealed interface of state records and a switch with pattern matching |
| Callers should loop over contents without seeing storage | Iterator | Implement Iterable, or return a Stream |
Try it yourself
A strategy for rounding
The shop rounds cash totals to the nearest 5 cents, because the shop has stopped giving out pennies, but card totals are exact. Write two IntUnaryOperator strategies, exact and toNickel, where toNickel returns Math.round(cents / 5.0f) * 5, and use the right one for each payment.
The program should print card: 1017 and cash: 1015.
import java.util.function.IntUnaryOperator;
public class Main {
static int total(int cents, IntUnaryOperator rounding) { return rounding.applyAsInt(cents); }
public static void main(String[] args) {
int due = 1017;
IntUnaryOperator exact = c -> c;
System.out.println("card: " + total(due, exact));
System.out.println("cash: " + total(due, exact));
}
}Try it yourself
Refuse a bad transition
The starter lets a rental go from Booked straight to Returned. Change next so that a Booked rental can only be picked up (event pickup gives Out), an Out rental can only be returned (event return gives Returned), and anything else throws IllegalStateException with the message not allowed.
The program should print pickup -> Out[], rejected: not allowed and return -> Returned[].
public class Main {
sealed interface Rental permits Booked, Out, Returned {}
record Booked() implements Rental {}
record Out() implements Rental {}
record Returned() implements Rental {}
static Rental next(Rental r, String event) {
return event.equals("pickup") ? new Out() : new Returned();
}
public static void main(String[] args) {
Rental r = new Booked();
for (String e : new String[] {"pickup", "pickup", "return"}) {
try { r = next(r, e); System.out.println(e + " -> " + r); }
catch (IllegalStateException ex) { System.out.println("rejected: " + ex.getMessage()); }
}
}
}Common mistakes
MistakeChoosing an algorithm with a long if-else chain on a flag.
InsteadMake each algorithm a strategy behind one interface and pass the one you want.
MistakeHaving the stock code call the screen and the reorder list directly.
InsteadLet observers register and have the subject notify a listener interface.
MistakeChanging stock with direct method calls that cannot be reversed.
InsteadRepresent each change as a command object that can be applied and undone.
MistakeChecking a status code with if statements in every method.
InsteadRepresent each state as a type and allow only the valid transitions.
MistakeWriting a 1994-style class for every small behavior.
InsteadUse lambdas, records and sealed types where they express the pattern more simply.
Summary and key terms
- Behavioral patterns are about how objects share responsibilities and communicate, often by turning a piece of behavior into an object.
- Strategy puts interchangeable algorithms behind one interface; a Comparator is a strategy.
- Observer lets a subject notify registered listeners without knowing what they do.
- Command turns a request into an object that can be queued, logged or undone; records implementing a sealed interface express commands well.
- Template method fixes an algorithm's skeleton in a final method and leaves some steps to subclasses, or to functions passed in.
- State represents each status as a type and allows only valid transitions, which sealed interfaces and pattern matching make compact.
- Iterator lets callers visit contents without seeing how they are stored, through Iterable or a Stream.
- Functional interfaces, lambdas, records and sealed types make most behavioral patterns much shorter than their 1994 forms.
- Behavioral pattern
- A pattern about how objects share responsibilities and communicate.
- Functional interface
- An interface with a single abstract method, which a lambda can implement.
- Strategy
- A family of interchangeable algorithms behind one interface, chosen at run time.
- Observer
- A pattern in which a subject notifies registered listeners when something happens.
- Subject
- In the observer pattern, the object whose events others want to hear about.
- Listener
- An observer, usually a small interface or lambda that receives notifications.
- Command
- A request turned into an object that can be stored, logged, queued or undone.
- Template method
- A method that fixes the steps of an algorithm and leaves some steps to subclasses.
- State
- A pattern in which each status of an object is its own type with its own allowed actions.
- Transition
- A move from one state to another, triggered by an event.
- Iterator
- An object that visits the elements of a collection one at a time.
- Iterable
- A Java interface whose iterator method lets a class be used in an enhanced for loop.
Practice problems
Work each problem on paper first, then reveal the answer to check.
What is the strategy in Collections.sort(list, comparator)?
Show answer
The Comparator.
Why does the shelf print its first low-stock message only after the second sale?
Show answer
After the first sale 5 tubes are left, which is not below the minimum of 5.
What makes a command undoable?
Show answer
It is an object that stores what it changed and has an undo method that reverses it.
Why is Report.print declared final?
Show answer
So subclasses can fill in steps but cannot change the order of the template.
How does a sealed Status interface help the state pattern?
Show answer
The compiler knows every state, so a switch can be checked for completeness.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.