Java Programming
Structural and Behavioral Design Patterns in Java
Intermediate9 min readUpdated
Structural patterns decide how objects are composed; behavioral patterns decide how they collaborate and share responsibility. This guide works through the ones you will meet in every serious Java codebase — Adapter, Decorator, Facade, Proxy and Composite; Strategy, Observer, Command, Template Method, Chain of Responsibility, State and Visitor — with idiomatic Java 21 implementations, the places they appear in the JDK and Spring, and the ways lambdas, sealed types and pattern matching simplify them.
What you will learn
- Recognise Adapter, Decorator, Facade, Proxy and Composite in library and framework code
- Implement Strategy, Command and Observer with functional interfaces where appropriate
- Apply Template Method, Chain of Responsibility and State to remove conditionals
- Replace Visitor with sealed interfaces and pattern-matching switch where it fits
- Explain how Spring's proxies and the java.io streams embody these patterns
Once objects exist, two questions remain: how to combine them into larger structures, and how to divide behaviour among them so that each change touches one place. The structural and behavioral patterns from the classic catalogue answer those questions, and unlike some of the creational patterns they have aged well — most of them are visible in the JDK, in Spring and in every web framework. This guide takes the twelve you are most likely to use or encounter, gives each a Java 21 implementation, and shows where modern language features shrink the classic form. The creational patterns are covered separately.
Structural patterns: composing objects
Adapter
Intent: convert the interface of a class into the one a client expects, so classes that could not otherwise work together can.
You need an adapter when you own the calling code and the called code but not the interface between them — typically integrating a third-party library into your own abstraction:
public interface PaymentGateway {
PaymentResult charge(Money amount, CardToken card);
}
// Third-party SDK with a different vocabulary
public final class StripeGatewayAdapter implements PaymentGateway {
private final StripeClient stripe;
public StripeGatewayAdapter(StripeClient stripe) { this.stripe = stripe; }
@Override
public PaymentResult charge(Money amount, CardToken card) {
ChargeResponse response = stripe.charges().create(
new ChargeRequest(amount.minorUnits(), amount.currency().code(), card.value()));
return response.succeeded()
? new Approved(response.id())
: new Declined(response.failureCode());
}
}
Application code depends on PaymentGateway; the adapter translates types, units and error models in one place. Arrays.asList (array to List), InputStreamReader (byte stream to character reader) and Collections.enumeration are JDK adapters. The pattern is the cleanest way to keep a vendor SDK from leaking through a codebase, and it makes the vendor replaceable.
Decorator
Intent: attach responsibilities to an object dynamically by wrapping it in an object with the same interface.
Decorators stack: each one implements the interface, holds another instance of it, and adds something before or after delegating. The java.io stream classes are the canonical example — new BufferedInputStream(new GZIPInputStream(new FileInputStream(f))) — and the I/O guide shows them in use. In service code the same shape adds cross-cutting behaviour without touching the core class:
public interface ProductCatalogue {
Optional<Product> find(String sku);
}
public final class CachingCatalogue implements ProductCatalogue {
private final ProductCatalogue delegate;
private final Map<String, Optional<Product>> cache = new ConcurrentHashMap<>();
public CachingCatalogue(ProductCatalogue delegate) { this.delegate = delegate; }
@Override
public Optional<Product> find(String sku) {
return cache.computeIfAbsent(sku, delegate::find);
}
}
public final class TimingCatalogue implements ProductCatalogue {
private final ProductCatalogue delegate;
private final MeterRegistry metrics;
// ... constructor
@Override
public Optional<Product> find(String sku) {
long start = System.nanoTime();
try {
return delegate.find(sku);
} finally {
metrics.timer("catalogue.find").record(Duration.ofNanos(System.nanoTime() - start));
}
}
}
ProductCatalogue catalogue = new TimingCatalogue(new CachingCatalogue(new DatabaseCatalogue(ds)), metrics);
The order of wrapping is the order of behaviour, which is both the power and the trap: timing outside caching measures cache hits too; caching outside timing measures only misses. Collections.unmodifiableList and synchronizedList are decorators; so is every Spring AOP advice, which is why the next pattern matters.
Proxy
Intent: provide a surrogate that controls access to another object.
A proxy has the same interface as its subject and, unlike a decorator, exists to manage the subject: create it lazily, guard it with a permission check, forward calls to a remote implementation, or intercept calls for a framework. Java can generate proxies at run time:
public interface AccountService { void close(String accountId); }
AccountService real = new DefaultAccountService();
AccountService guarded = (AccountService) Proxy.newProxyInstance(
AccountService.class.getClassLoader(),
new Class<?>[] { AccountService.class },
(proxy, method, args) -> {
if (!currentUser().hasRole("ADMIN")) {
throw new AccessDeniedException(method.getName());
}
return method.invoke(real, args); // InvocationHandler: intercept every call
});
java.lang.reflect.Proxy works for interfaces; CGLIB and ByteBuddy subclass concrete classes. This is exactly how Spring implements @Transactional, @Cacheable, @Async and security annotations: the bean you inject is a proxy around your object, and the annotation's behaviour runs in the interception layer. It also explains the classic Spring puzzle — a @Transactional method called from another method in the same class is not transactional, because the internal call never passes through the proxy. JPA lazy-loading entities and RMI stubs are proxies too.
Facade
Intent: provide a single, simplified interface to a subsystem.
A facade does not add behaviour; it hides a set of collaborating classes behind one entry point so callers need not know the choreography:
public final class CheckoutFacade {
private final InventoryService inventory;
private final PaymentGateway payments;
private final OrderRepository orders;
private final Notifier notifier;
// ... constructor
public OrderConfirmation checkout(Cart cart, CardToken card) {
ReservationToken reservation = inventory.reserve(cart.lines());
PaymentResult payment = payments.charge(cart.total(), card);
if (payment instanceof Declined d) {
inventory.release(reservation);
throw new PaymentDeclinedException(d.reason());
}
Order order = orders.save(Order.from(cart, payment));
notifier.orderPlaced(order);
return new OrderConfirmation(order.id());
}
}
An application service in a layered architecture is a facade over the domain; javax.crypto.Cipher is a facade over providers; Files is arguably a facade over filesystem providers. The pattern is often the first refactoring to apply to a controller that has grown to orchestrate five services itself.
Composite
Intent: compose objects into tree structures and let clients treat individual objects and compositions uniformly.
Whenever a thing can contain things of its own kind — directories and files, UI containers and widgets, menu groups and items, expression nodes — Composite gives both the leaf and the container the same interface so that operations recurse naturally:
public sealed interface Expense permits LineItem, ExpenseGroup {
long totalCents();
}
public record LineItem(String label, long cents) implements Expense {
@Override public long totalCents() { return cents; }
}
public record ExpenseGroup(String label, List<Expense> children) implements Expense {
@Override public long totalCents() {
return children.stream().mapToLong(Expense::totalCents).sum(); // recursion through the interface
}
}
A caller asks any Expense for its total and never checks whether it is a group. Swing's Container extends Component, the DOM, and the Path of a filesystem walk are Composites. The pattern's cost is that operations meaningful only for containers (add, remove) either pollute the leaf interface or require a cast; keeping them on the container type only, as above, is the safer choice.
Bridge and Flyweight round out the structural set. Bridge separates an abstraction from its implementation so both can vary — JDBC's Connection over many drivers — and in practice looks like "program to an interface and inject the implementation". Flyweight shares immutable state among many objects to save memory; Integer.valueOf caching small values and String interning are the JDK's examples, and records with equals-based deduplication in a map are the modern way to build one.
Behavioral patterns: assigning responsibility
Strategy
Intent: define a family of interchangeable algorithms and let the client pick one at run time.
Strategy replaces a conditional over "which algorithm" with polymorphism. Before lambdas each strategy was a class; now a single-method strategy is a functional interface, and a named interface is kept where the domain name earns it:
@FunctionalInterface
public interface ShippingRule {
Money cost(Shipment shipment);
static ShippingRule flat(Money amount) { return s -> amount; }
static ShippingRule perKilo(Money perKilo) { return s -> perKilo.times(s.weightKg()); }
static ShippingRule freeAbove(Money threshold, ShippingRule otherwise) {
return s -> s.orderValue().isGreaterThan(threshold) ? Money.ZERO : otherwise.cost(s);
}
}
Map<Region, ShippingRule> rules = Map.of(
Region.EU, ShippingRule.freeAbove(Money.eur(50), ShippingRule.flat(Money.eur(4))),
Region.US, ShippingRule.perKilo(Money.usd(3)));
Money cost = rules.get(shipment.region()).cost(shipment);
Comparator is the JDK's most-used Strategy; so are ThreadFactory, RejectedExecutionHandler and every Function you pass to a stream. A Map from key to strategy, as above, replaces a switch that would need editing each time a case is added.
Template Method
Intent: fix the skeleton of an algorithm in a superclass and let subclasses override specific steps.
The inheritance guide shows the classic abstract-class form. Its strength is guaranteeing the order of steps; its weakness is that it uses inheritance, so a class can follow only one template and the coupling is tight. The functional alternative passes the variable steps as parameters, which is how Spring's JdbcTemplate, TransactionTemplate and RestTemplate work: the template owns resource acquisition, exception translation and cleanup, and a callback supplies the middle. When you find yourself writing the same try/finally around different bodies, that is a template waiting to be extracted.
Observer
Intent: when one object changes state, notify all dependents automatically without the subject knowing who they are.
public final class OrderTracker {
private final List<Consumer<OrderEvent>> listeners = new CopyOnWriteArrayList<>();
public Runnable subscribe(Consumer<OrderEvent> listener) {
listeners.add(listener);
return () -> listeners.remove(listener); // unsubscribe handle
}
void publish(OrderEvent event) {
for (Consumer<OrderEvent> l : listeners) {
try {
l.accept(event);
} catch (RuntimeException e) {
log.warn("Listener failed for {}", event, e); // one bad listener must not stop the rest
}
}
}
}
CopyOnWriteArrayList makes it safe for a listener to unsubscribe during notification. Two design questions decide whether an Observer implementation causes trouble: who owns the thread — synchronous notification blocks the publisher and inherits its transaction, asynchronous notification needs an executor and loses ordering guarantees; and how listeners are removed — a forgotten listener is a memory leak, which is why the subscribe method returns an unsubscribe handle. Spring's ApplicationEventPublisher with @EventListener (and @TransactionalEventListener to fire after commit) is the pattern with the bookkeeping done for you; java.util.Observable is deprecated and PropertyChangeSupport survives mainly in desktop code.
Command
Intent: encapsulate a request as an object so that it can be queued, logged, undone or executed later.
A Runnable is a Command with no undo, and ExecutorService.submit is the invoker. The pattern earns its full form when commands need identity and reversal:
public interface EditorCommand {
void execute(Document doc);
void undo(Document doc);
}
public record InsertText(int offset, String text) implements EditorCommand {
@Override public void execute(Document doc) { doc.insert(offset, text); }
@Override public void undo(Document doc) { doc.delete(offset, text.length()); }
}
public final class CommandHistory {
private final Deque<EditorCommand> done = new ArrayDeque<>();
private final Document doc;
// ... constructor
public void run(EditorCommand cmd) { cmd.execute(doc); done.push(cmd); }
public void undo() { if (!done.isEmpty()) done.pop().undo(doc); }
}
Records make commands cheap, serialisable-by-hand and easy to log. Beyond editors, Command underlies job queues, CQRS command handlers, transactional outboxes and audit logs: anything where "what was asked" must survive independently of "who does it".
Chain of Responsibility
Intent: pass a request along a chain of handlers until one deals with it, so the sender is decoupled from the receiver.
Servlet filters, Spring Security's filter chain, HTTP client interceptors and logging appenders are all chains. The modern form is a list of handlers with a next continuation:
@FunctionalInterface
public interface Handler {
Response handle(Request request, Chain chain);
interface Chain { Response proceed(Request request); }
}
public final class Pipeline {
private final List<Handler> handlers;
private final Function<Request, Response> terminal;
// ... constructor
public Response run(Request request) { return proceed(0, request); }
private Response proceed(int index, Request request) {
if (index == handlers.size()) return terminal.apply(request);
return handlers.get(index).handle(request, r -> proceed(index + 1, r));
}
}
Pipeline pipeline = new Pipeline(List.of(
(req, chain) -> req.hasValidToken() ? chain.proceed(req) : Response.unauthorised(),
(req, chain) -> { log.info("{} {}", req.method(), req.path()); return chain.proceed(req); },
(req, chain) -> rateLimiter.allow(req.clientId()) ? chain.proceed(req) : Response.tooManyRequests()),
controller::dispatch);
Each handler decides whether to stop, transform the request, or call chain.proceed. Because a handler can also act after proceed returns, the chain doubles as a stack of around-advice. Keep handlers stateless and order them explicitly; a chain assembled from classpath scanning in undefined order is a debugging nightmare.
State
Intent: let an object change its behaviour when its internal state changes, by delegating to a state object.
State replaces a switch (status) repeated across every method with one class (or enum constant) per state that knows its own transitions:
public enum OrderStatus {
NEW {
@Override OrderStatus pay() { return PAID; }
@Override OrderStatus cancel() { return CANCELLED; }
},
PAID {
@Override OrderStatus ship() { return SHIPPED; }
@Override OrderStatus cancel() { return REFUNDED; }
},
SHIPPED, CANCELLED, REFUNDED;
OrderStatus pay() { throw new IllegalStateException("Cannot pay from " + this); }
OrderStatus ship() { throw new IllegalStateException("Cannot ship from " + this); }
OrderStatus cancel() { throw new IllegalStateException("Cannot cancel from " + this); }
}
Enum constants with bodies are the lightest State implementation in Java: every transition is in one place, invalid transitions fail loudly, and the compiler lists all states. When states carry data or need injected services, use a sealed interface with a record per state and switch over it. Either way, the pattern's benefit is that adding a state means adding a class, not editing every method.
Visitor, and its sealed-type replacement
Intent: represent an operation to be performed on the elements of an object structure, without changing the element classes.
Classic Visitor achieves double dispatch — behaviour chosen by both the element type and the operation — with an accept(Visitor) method on every element and a visitX method per element type on the visitor. Adding an operation is easy (a new visitor); adding an element type is painful (every visitor changes). It is the right shape for compilers and document models with many operations over a stable set of node types, and it is how the JDK's javax.lang.model and FileVisitor APIs are built.
Java 21 offers a lighter route for hierarchies you own: seal the interface and switch with record patterns.
public sealed interface Shape permits Circle, Rectangle, Group {}
record Circle(double radius) implements Shape {}
record Rectangle(double w, double h) implements Shape {}
record Group(List<Shape> children) implements Shape {}
static double area(Shape shape) {
return switch (shape) {
case Circle(double r) -> Math.PI * r * r;
case Rectangle(double w, double h) -> w * h;
case Group(List<Shape> kids) -> kids.stream().mapToDouble(Program::area).sum();
};
}
Each operation is one exhaustive function; adding a shape breaks every switch at compile time, which is the guarantee Visitor provided through the interface. Keep classic Visitor when the hierarchy is open, lives in another module, or when a visitor instance needs to accumulate state across a traversal in a reusable way.
Iterator, Mediator, Memento and Interpreter complete the behavioural catalogue. Iterator is built into the language via Iterable and the for-each loop; implement it for your own aggregates so they work with streams (StreamSupport.stream(spliterator(), false)). Mediator centralises communication between components — a controller between form fields, a message broker between services. Memento captures state for later restoration; an immutable snapshot record is usually all it takes. Interpreter builds an evaluator over a grammar and is another natural fit for sealed types.
Common mistakes
Pattern-driven design. Choosing patterns first and looking for places to use them produces abstract factories of strategy visitors that nobody can follow. Start from the duplication or the change you cannot make cleanly, then name the fix.
Decorator order left implicit. Wrapping in the wrong order (retry outside timeout, or caching outside authorisation) changes semantics silently. Document the order or build it in one factory method.
Self-invocation through a proxy. Calling an annotated method from within the same Spring bean bypasses the proxy; move the method to another bean or inject the bean into itself only as a last resort.
Observers that never unsubscribe. The subject holds a strong reference, so the listener and everything it references live forever. Return unsubscribe handles and call them.
Blocking or throwing inside listeners. A slow listener stalls the publisher; an exception can stop later listeners. Isolate each call and consider an executor.
Strategy classes for one-liners. A PlusOneStrategy class implementing IntUnaryOperator is a lambda in a costume.
Visitor for an open hierarchy you cannot seal. Every new type breaks all visitors; use a default method or a switch with a default and accept the loss of exhaustiveness.
Mutable state in shared handlers. Filters and chain handlers are used concurrently; a field that changes per request is a race.
Key takeaways
- Adapter changes an interface, Decorator adds behaviour behind the same interface, Proxy controls access — all by wrapping, and all visible in
java.io, the collections utilities and Spring AOP. - Facade simplifies a subsystem behind one entry point; Composite lets trees be treated as single objects through a shared interface.
- Strategy, Command and Observer are now largely functional interfaces, lambdas and
Consumerlists; keep named types where domain meaning or multiple methods justify them. - Template Method fixes the order of steps; its callback form (
JdbcTemplate) avoids inheritance. - Chain of Responsibility and State remove conditionals: handlers with a
proceedcontinuation, and enum constants or sealed records that own their transitions. - Sealed interfaces plus pattern-matching
switchreplace Visitor for hierarchies you control, keeping exhaustiveness without the boilerplate.
Sources and further reading
Frequently asked questions
- What is the difference between Decorator, Proxy and Adapter?
- All three wrap an object, but for different reasons. An Adapter changes the interface so an existing class fits where a different type is expected. A Decorator keeps the same interface and adds behaviour, and decorators stack. A Proxy also keeps the interface but controls access to the real object — lazily creating it, checking permissions, adding remoting or caching — and the client usually does not know it is there.
- Do lambdas make the Strategy pattern obsolete?
- They make the class hierarchy optional. When a strategy is a single operation, a functional interface plus lambdas or method references is the Strategy pattern with less code. Keep a named interface and classes when the strategy has several methods, needs configuration or state, or when the name conveys domain meaning that a bare Function would lose.
- Should I use the Observer pattern or an event bus?
- Direct Observer — a subject holding a list of listeners — is right within one component and is what UI toolkits and PropertyChangeSupport use. Once several unrelated components react to the same events, an in-process event mechanism such as Spring's ApplicationEventPublisher decouples publishers from subscribers and lets you make handlers asynchronous or transactional. Across processes, use a message broker.
- Is Visitor still needed now Java has pattern matching?
- For your own closed hierarchies, a sealed interface and a switch with record patterns give the same double dispatch with exhaustiveness checking and far less boilerplate. Visitor remains useful when the hierarchy is not sealed, when it lives in a library you cannot change, or when you want the visitor object itself to be a reusable, stateful component that is passed around.