JAVA-270 · Lesson 4 of 12 · 23 min
Structural patterns
▶ Video coming soon A video version of this lesson is on the way.
Tuesday, February 1, 2028. Kofi joins the session for the first half hour, because he has a problem that is really a design problem. The shop's supplier, Velotek, has replaced its old price list with a web service, and the library Velotek gives its customers does not look anything like the PriceList interface Hamza's code expects: it returns prices as text in dollars, it wants a customer number on every call, and it is slow. Kofi wants the counter program to use the new service without rewriting everything that asks for prices. Ingrid says that is the first of five structural patterns on tonight's list, all of them about fitting objects together.
What structural patterns do
Structural patterns describe ways to combine classes and objects into larger structures while keeping each piece simple. Most of them work by wrapping: one object holds another and stands in front of it, sharing or translating its interface. They differ in why they wrap. An adapter changes an interface so it fits. A decorator keeps the interface and adds behaviour. A facade offers a simpler interface to several objects. A composite lets a group be treated like a single item. A proxy controls access to the object behind it.
Adapter
An adapter converts the interface of a class into the interface its clients expect, so classes that could not otherwise work together can. It is the travel plug of software. The client code keeps talking to the interface it knows; the adapter translates each call into whatever the other class needs, and translates the answers back.
import java.math.BigDecimal;
import java.util.Map;
public class Main {
interface PriceList { int cents(String code); }
static final class VelotekClient {
private final Map<String, String> catalog = Map.of("VT-TUBE-70025", "8.99", "VT-PAD-ROAD", "14.99");
String lookUpPrice(String customerNumber, String velotekCode) {
if (!customerNumber.equals("SG-0418")) throw new IllegalArgumentException("bad customer");
return catalog.getOrDefault(velotekCode, "0.00");
}
}
static final class VelotekPriceList implements PriceList {
private final VelotekClient client;
private final String customer;
private final Map<String, String> codes = Map.of("TUBE-700x25", "VT-TUBE-70025", "PAD-ROAD", "VT-PAD-ROAD");
VelotekPriceList(VelotekClient client, String customer) { this.client = client; this.customer = customer; }
public int cents(String code) {
String text = client.lookUpPrice(customer, codes.get(code));
return new BigDecimal(text).movePointRight(2).intValueExact();
}
}
public static void main(String[] args) {
PriceList prices = new VelotekPriceList(new VelotekClient(), "SG-0418");
System.out.println("TUBE-700x25 " + prices.cents("TUBE-700x25"));
System.out.println("PAD-ROAD " + prices.cents("PAD-ROAD"));
}
}TUBE-700x25 899 PAD-ROAD 1499
What this code does
VelotekClient stands in for the supplier's library, with its own method name, its own part codes, a customer number and prices as text in dollars. VelotekPriceList implements the shop's PriceList interface and translates each call: it maps the shop's code to Velotek's, adds the customer number and converts the text price to whole cents with BigDecimal. Nothing that already asks a PriceList for prices has to change.
Adapters are among the most useful patterns in real work, because almost every program has to talk to code it did not write: a supplier's library, a payment terminal, an old part of the program itself. An adapter keeps the foreign interface at the edge, in one class, so when Velotek changes its library again only the adapter changes. Lesson 8 builds a whole architecture on this idea.
The adapter used BigDecimal to read a price like 8.99. A double cannot hold 8.99 exactly, and converting it with a multiplication can produce 898 instead of 899; BigDecimal reads the decimal text exactly and intValueExact refuses anything that is not a whole number of cents.
Decorator
A decorator wraps an object that implements an interface and implements the same interface itself, adding behaviour before or after passing each call on. Because the decorator has the same interface as the thing it wraps, decorators can be stacked, and the client cannot tell how many layers there are. The Java library uses decorators throughout java.io: a BufferedReader wraps an InputStreamReader, which wraps a FileInputStream, and each adds one feature.
The Velotek service is slow, so Kofi wants prices cached for the day. He also wants to know how many times the service is actually called. Both features wrap the price list without changing it.
import java.util.*;
public class Main {
interface PriceList { int cents(String code); }
static final class SlowSupplier implements PriceList {
public int cents(String code) { return code.equals("BELL") ? 650 : 899; }
}
static final class CountingPrices implements PriceList {
private final PriceList inner;
int calls;
CountingPrices(PriceList inner) { this.inner = inner; }
public int cents(String code) { calls++; return inner.cents(code); }
}
static final class CachingPrices implements PriceList {
private final PriceList inner;
private final Map<String, Integer> cache = new HashMap<>();
CachingPrices(PriceList inner) { this.inner = inner; }
public int cents(String code) { return cache.computeIfAbsent(code, inner::cents); }
}
public static void main(String[] args) {
CountingPrices counted = new CountingPrices(new SlowSupplier());
PriceList prices = new CachingPrices(counted);
int total = 0;
for (String code : List.of("TUBE-700x25", "BELL", "TUBE-700x25", "TUBE-700x25", "BELL")) total += prices.cents(code);
System.out.println("order total: " + total);
System.out.println("supplier calls: " + counted.calls);
}
}order total: 3997 supplier calls: 2
What this code does
CountingPrices and CachingPrices both implement PriceList and both wrap another PriceList, so they can be stacked in either order around the real supplier. The cache sits outside, so of five lookups only the first for each part reaches the counting layer and the supplier. The order total is the same as without decorators, but the supplier is called twice instead of five times.
The decorator pattern is the open/closed principle at work: caching and counting were added without touching SlowSupplier or the code that uses PriceList. The alternative, a subclass for every combination, CachingCountingSupplier and so on, grows out of control as features multiply. Lesson 6 returns to that point.
Because PriceList has only one method, a decorator can also be written as a lambda that wraps another lambda, for example code -> { log(code); return inner.cents(code); }. Small decorators are often written that way in modern Java; a class is clearer when the decorator keeps state, as both of these do.
Facade
A facade provides one simple interface to a group of classes that work together, so clients can do common jobs without knowing the details of each part. A facade does not hide the parts from clients that need them; it just offers a convenient front door for the usual case.
At the counter, selling a part involves checking stock, getting the price, adding tax, reserving the stock and printing a receipt, five different objects in CounterApp. The volunteers at the till should not have to know about any of them. A checkout facade offers one method.
import java.util.*;
public class Main {
static final class Stock {
private final Map<String, Integer> counts = new TreeMap<>(Map.of("BELL", 3, "TUBE-700x25", 14));
boolean has(String code, int n) { return counts.getOrDefault(code, 0) >= n; }
void take(String code, int n) { counts.merge(code, -n, Integer::sum); }
int left(String code) { return counts.get(code); }
}
static final class Prices { int cents(String code) { return code.equals("BELL") ? 650 : 899; } }
static final class Tax { int on(int cents) { return Math.round(cents * 13 / 100.0f); } }
static final class ReceiptPrinter { void print(String line) { System.out.println(" " + line); } }
static final class Checkout {
private final Stock stock = new Stock();
private final Prices prices = new Prices();
private final Tax tax = new Tax();
private final ReceiptPrinter printer = new ReceiptPrinter();
boolean sell(String code, int qty) {
if (!stock.has(code, qty)) { printer.print("not enough " + code); return false; }
int sub = prices.cents(code) * qty, t = tax.on(sub);
stock.take(code, qty);
printer.print(qty + " x " + code + " = " + sub + " + HST " + t + " = " + (sub + t));
return true;
}
int left(String code) { return stock.left(code); }
}
public static void main(String[] args) {
Checkout till = new Checkout();
System.out.println("sale 1:");
till.sell("TUBE-700x25", 2);
System.out.println("sale 2:");
till.sell("BELL", 4);
System.out.println("tubes left: " + till.left("TUBE-700x25"));
}
}sale 1: 2 x TUBE-700x25 = 1798 + HST 234 = 2032 sale 2: not enough BELL tubes left: 12
What this code does
Checkout is a facade: one sell method coordinates stock, prices, tax and the receipt printer, in the right order, so the till code needs to know only one class. The parts still exist and can be used directly by code that needs them, such as the stock report. The second sale is refused because only three bells are in stock.
In this example the facade creates its parts itself to keep the code short. In the real counter program they would be passed in through the constructor, as lesson 3 recommended, so the facade could be tested with a fake stock.
Composite
A composite lets clients treat individual objects and groups of objects in the same way. A single part and a kit of parts both answer the same questions, such as what is your price, and a kit can contain other kits. The structure is a tree, and code that works on one item works on the whole tree.
Second Gear sells kits: a commuter kit has a bell, lights and a lock; a winter tune-up kit has a chain, brake pads and the commuter kit's lights. Odile wants the price of a kit to be the sum of its contents less 10 in 100, and kits can contain kits.
import java.util.*;
public class Main {
sealed interface Item permits Part, Kit {
String name();
int cents();
}
record Part(String name, int cents) implements Item {}
record Kit(String name, List<Item> contents) implements Item {
public int cents() {
int sum = contents.stream().mapToInt(Item::cents).sum();
return sum - sum / 10;
}
}
static void show(Item item, String indent) {
System.out.println(indent + item.name() + " " + item.cents());
if (item instanceof Kit k) for (Item i : k.contents()) show(i, indent + " ");
}
public static void main(String[] args) {
Kit lights = new Kit("light set", List.of(new Part("front light", 2400), new Part("rear light", 1600)));
Kit commuter = new Kit("commuter kit", List.of(new Part("bell", 650), lights, new Part("lock", 3500)));
Kit winter = new Kit("winter kit", List.of(new Part("chain", 3999), new Part("brake pads", 1499), lights));
show(commuter, "");
show(winter, "");
}
}commuter kit 6975
bell 650
light set 3600
front light 2400
rear light 1600
lock 3500
winter kit 8189
chain 3999
brake pads 1499
light set 3600
front light 2400
rear light 1600What this code does
Part and Kit both implement Item, so anything that asks for a price can be given a single part or a whole kit. A kit's price is the sum of its contents minus a tenth, and because a kit's contents are Items, kits can contain kits to any depth. The show method walks the tree with the same code at every level.
A sealed interface with records, as here, is a natural modern form of the composite. The sealed permits clause lists the two kinds of item, so a switch over an Item can be checked by the compiler to cover both.
Proxy
A proxy stands in for another object and controls access to it. From the outside it looks exactly like the real object, because it implements the same interface. Proxies differ in what they control: a protection proxy checks permissions, a virtual proxy delays creating an expensive object until it is needed, and a remote proxy hides the fact that the real object is on another computer.
The structure is the same as a decorator's, and the difference is intent. A decorator adds features to an object; a proxy decides whether, when and how the real object is reached. At Second Gear, refunds over 50 dollars need a staff member, not a volunteer.
public class Main {
interface Refunds { String refund(String who, int cents); }
static final class TillRefunds implements Refunds {
public String refund(String who, int cents) { return "refunded " + cents + " cents (by " + who + ")"; }
}
static final class StaffOnlyRefunds implements Refunds {
private final Refunds real;
private final java.util.Set<String> staff;
StaffOnlyRefunds(Refunds real, java.util.Set<String> staff) { this.real = real; this.staff = staff; }
public String refund(String who, int cents) {
if (cents > 5000 && !staff.contains(who)) return "refused: refunds over 5000 cents need staff, not " + who;
return real.refund(who, cents);
}
}
public static void main(String[] args) {
Refunds refunds = new StaffOnlyRefunds(new TillRefunds(), java.util.Set.of("Odile", "Kofi"));
System.out.println(refunds.refund("Sam", 1200));
System.out.println(refunds.refund("Sam", 8999));
System.out.println(refunds.refund("Kofi", 8999));
}
}refunded 1200 cents (by Sam) refused: refunds over 5000 cents need staff, not Sam refunded 8999 cents (by Kofi)
What this code does
StaffOnlyRefunds is a protection proxy: it implements the same Refunds interface as the real till and stands in front of it. Small refunds pass straight through, but a refund over 5000 cents reaches the till only if the person asking is on the staff list. Code that issues refunds cannot tell it is talking to a proxy.
Telling the wrappers apart
| Pattern | Interface of the wrapper | Purpose | Second Gear example |
|---|---|---|---|
| Adapter | Different from the wrapped object | Make an existing class fit the interface clients expect | Velotek client as a PriceList |
| Decorator | Same as the wrapped object | Add behaviour, stackable in layers | Caching and counting prices |
| Facade | New and simpler | One front door to several objects | Checkout.sell |
| Composite | Same for single items and groups | Treat trees of objects uniformly | Kits of parts and kits |
| Proxy | Same as the wrapped object | Control access to the real object | Staff-only refunds |
Try it yourself
Write a logging decorator
Add a class LoggingStock implements Stock that wraps another Stock and prints asked for CODE before passing each count call on. Wrap the real stock with it in main without changing InMemoryStock.
The program should print asked for BELL, bells: 3, asked for LOCK and locks: 0.
import java.util.*;
public class Main {
interface Stock { int count(String code); }
static final class InMemoryStock implements Stock {
private final Map<String, Integer> m = Map.of("BELL", 3);
public int count(String code) { return m.getOrDefault(code, 0); }
}
public static void main(String[] args) {
Stock stock = new InMemoryStock();
System.out.println("bells: " + stock.count("BELL"));
System.out.println("locks: " + stock.count("LOCK"));
}
}Try it yourself
Count the parts in a kit
Add a method int partCount() to the Item interface. A Part counts as 1, and a Kit's count is the sum of its contents' counts. Print the count for the commuter kit, which contains a light set.
The program should print commuter kit has 4 parts.
import java.util.*;
public class Main {
sealed interface Item permits Part, Kit { String name(); }
record Part(String name) implements Item {}
record Kit(String name, List<Item> contents) implements Item {}
public static void main(String[] args) {
Kit lights = new Kit("light set", List.of(new Part("front light"), new Part("rear light")));
Kit commuter = new Kit("commuter kit", List.of(new Part("bell"), lights, new Part("lock")));
System.out.println(commuter.name() + " has " + commuter.contents().size() + " parts");
}
}Common mistakes
MistakeChanging working code to fit a foreign library's interface.
InsteadWrite an adapter at the edge that translates between the two.
MistakeA subclass for every combination of extra features.
InsteadStack decorators that share the wrapped object's interface.
MistakeMaking clients call five objects in the right order for a common job.
InsteadOffer a facade with one method for the usual case.
Mistakeinstanceof checks to tell single items from groups everywhere.
InsteadGive items and groups the same interface with a composite.
MistakeMixing up decorator and proxy.
InsteadBoth wrap with the same interface; a decorator adds behaviour, a proxy controls access.
Summary and key terms
- Structural patterns combine objects into larger structures, mostly by wrapping one object in another.
- An adapter converts one interface into the one clients expect, keeping foreign code at the edge.
- A decorator implements the same interface as the object it wraps and adds behaviour, and decorators can be stacked, as java.io streams are.
- A facade gives one simple front door to several cooperating objects without hiding them.
- A composite gives single items and groups the same interface so trees of objects can be handled uniformly; sealed interfaces with records express it well.
- A proxy has the same interface as the real object and controls access to it, for protection, delayed creation or remote calls.
- BigDecimal reads decimal prices exactly where a double cannot.
- Structural pattern
- A pattern about combining classes and objects into larger structures.
- Wrapping
- Holding another object and standing in front of it, passing calls on.
- Adapter
- A class that makes an existing class fit the interface clients expect.
- Adaptee
- The class an adapter wraps, whose interface does not fit.
- Decorator
- A wrapper with the same interface as the wrapped object that adds behaviour.
- Facade
- A simple interface to a group of cooperating classes.
- Composite
- A structure in which single objects and groups share one interface.
- Leaf
- A single item in a composite, with no children.
- Proxy
- A stand-in with the same interface as the real object that controls access to it.
- Protection proxy
- A proxy that checks permissions before passing a call on.
- Virtual proxy
- A proxy that delays creating an expensive object until it is first needed.
- BigDecimal
- A Java class for exact decimal arithmetic, suited to money.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Velotek renames lookUpPrice. Which class changes?
Show answer
Only the adapter, VelotekPriceList.
In the decorator example, why are there only two supplier calls?
Show answer
The caching layer is outside the counter, so repeated codes are answered from the cache.
Does a facade stop other code from using the stock object directly?
Show answer
No; it adds a convenient front door but the parts stay available.
What is the price of a light set inside the winter kit?
Show answer
3600: 2400 plus 1600 less a tenth; the winter kit then sums it with the other parts and takes a tenth again.
A wrapper has the same interface and refuses some calls. Decorator or proxy?
Show answer
Proxy, because its purpose is controlling access.
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.