Skip to content
Tutorials Center
My learning

Topics

Lesson 160 of 201 ยท JVM and Advanced Topics

Structural and Behavioral Design Patterns

Learn the essential structural and behavioral design patterns in Java - adapter, decorator, facade, proxy, composite, strategy, observer, command, iterator, template method, state.

Creational patterns decide how objects are born. The rest of the classic catalog is about what happens next. Structural patterns describe how to combine objects into larger structures: wrapping one object to change its interface or add behavior, hiding a subsystem behind a simple front, treating trees of objects like single objects. Behavioral patterns describe how objects divide work and communicate: swapping algorithms, broadcasting events, turning requests into objects, letting an object change behavior when its state changes.

This lesson covers the eleven patterns you'll meet most often in real Java code, each with a runnable example and the places the JDK and popular frameworks use it. A recurring theme: many patterns that needed a family of classes in 1994 shrink to a few lines with lambdas and functional interfaces, because a single-method interface is a pluggable piece of behavior.

Structural patterns

Adapter

Intent: make a class with an incompatible interface work where a different interface is expected, without changing either side.

You meet this constantly at boundaries: a third-party library, a legacy module or a vendor SDK speaks a different "language" than your code. The adapter implements your interface and translates each call into the other API, exactly like a travel plug adapter.

Java Adapter: a legacy sensor behind a modern interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

JDK adapters: InputStreamReader adapts a byte stream to a character Reader, Arrays.asList adapts an array to a List, and Collections.enumeration / Enumeration.asIterator() bridge old and new iteration APIs. When the target is a functional interface, a method reference is an instant adapter: IntSupplier reading = probe::readTenthsF;.

Decorator

Intent: add responsibilities to an object dynamically by wrapping it in another object with the same interface.

Each decorator holds a reference to the object it wraps, forwards calls to it, and adds something before or after: logging, caching, retries, compression, validation. Because decorators share the interface, you can stack them in any combination, which avoids an explosion of subclasses like CachingLoggingRetryingRepository.

Java Decorator: stacking caching and logging

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

With Logging(Caching(remote)), the log shows every request, but the remote service is called only twice. Swap the order to Caching(Logging(remote)) and only cache misses are logged. Java I/O is the textbook decorator: new BufferedReader(new InputStreamReader(new GZIPInputStream(fileStream))) stacks buffering, decoding and decompression (see Byte and Character Streams). Collections.unmodifiableList and Collections.synchronizedMap are decorators too.

Facade

Intent: provide one simple interface to a complex subsystem.

A facade doesn't add new capabilities; it packages a common workflow so that callers don't need to know five classes and the right order to call them in. Callers that need fine control can still use the subsystem directly.

Proxy

Intent: provide a stand-in for another object to control access to it.

A proxy has the same interface as the real object, like a decorator, but its purpose is control rather than added features: create the real object only when first needed (virtual proxy), check permissions (protection proxy), or represent an object in another process (remote proxy). The reflection lesson built proxies at run time with java.lang.reflect.Proxy; here both patterns are written by hand:

Java Facade and proxy working together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The slow connection happens only when the first verified customer pays, not when the shop starts, and unverified customers never reach the real service. Spring wraps your beans in proxies for @Transactional, @Cacheable and security annotations; Hibernate uses virtual proxies for lazy-loaded entities. java.net.http.HttpClient and javax.sql.DataSource are good examples of facades over large subsystems.

Decorator, proxy, adapter: what's the difference? All three wrap an object. An adapter changes the interface. A decorator keeps the interface and adds behavior, and is usually stacked by the client. A proxy keeps the interface and controls access, and is usually invisible to the client.

Composite

Intent: compose objects into tree structures and let clients treat individual objects and groups the same way.

Files and folders, UI components and panels, menu items and submenus, prices of bundles that contain products and other bundles: in each case a group should respond to the same operations as a single item. With a sealed interface and records, a composite is short and the compiler checks that every operation handles both cases:

Java Composite: files and folders as one type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

size() works identically on one file and on the whole project, so client code never has to ask "is this a folder?" for common operations.

Behavioral patterns

Strategy

Intent: define a family of interchangeable algorithms, encapsulate each one, and let the client choose at run time.

Instead of an if/switch that selects the algorithm inside a class, the class receives the algorithm as an object. Comparator is the strategy you use every day: list.sort(byPrice) takes the sorting rule as a parameter. In modern Java, strategies are usually lambdas:

Java Strategy: pluggable pricing rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Adding a campaign means adding a strategy, never editing checkout: the open/closed principle in action. Static factory methods on the interface (percentOff, none) give the common strategies readable names.

Observer

Intent: when one object (the subject) changes, notify all registered observers automatically, without the subject knowing what they do.

This is the publish/subscribe idea behind GUI event listeners, domain events, and reactive streams. The subject keeps a list of listeners and calls each one when something happens. Listeners can be added and removed at run time, and the subject depends only on a listener interface.

Java Observer: price alerts with listeners

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

CopyOnWriteArrayList lets listeners unsubscribe while a notification is in progress without a ConcurrentModificationException (see Concurrent Collections). Two pitfalls to remember: a long-lived subject keeps every registered listener reachable, so forgotten listeners leak memory; and a listener that throws can stop the others from running unless the subject catches exceptions per listener. The old java.util.Observable class is deprecated; use your own listener interface, PropertyChangeSupport for beans, or java.util.concurrent.Flow for reactive streams with back-pressure.

Command

Intent: turn a request into an object, so you can queue it, log it, schedule it, or undo it.

A command object captures everything needed to perform an action later. Once actions are objects, an undo stack is just a Deque of commands that know how to reverse themselves:

Java Command: an editor with undo and redo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Commands also power task queues (ExecutorService.submit takes a Runnable or Callable, which are commands), menu actions and keyboard shortcuts in GUI apps, database migrations, and "event sourcing," where the history of commands is the data. For actions without undo, a Runnable or lambda is all the command you need.

Iterator

Intent: access the elements of a collection one by one without exposing how it's stored.

Java builds this pattern into the language: any class that implements Iterable<T> works in a for-each loop. You covered the mechanics in Iterators; the pattern's value shows when your own data structure needs traversal that callers shouldn't have to know about:

Java Iterator: working days as an Iterable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The caller writes a plain for-each loop, and the record computes each date on demand. The stream API is the next step of the same idea: internal iteration, where you hand the collection a lambda and it does the looping.

Template Method

Intent: define the skeleton of an algorithm in a base class and let subclasses fill in specific steps.

You saw it in Abstraction and Abstract Classes and, applied to creation, as the factory method. The base class has a final method that calls abstract (or overridable "hook") methods in a fixed order:

Java
abstract class DataImport {
    final void run() {             // the template: subclasses can't change the order
        var rows = read();
        rows = rows.stream().filter(this::isValid).toList();
        save(rows);
        afterImport(rows.size());  // a "hook" with a default
    }
    protected abstract List<String> read();
    protected abstract boolean isValid(String row);
    protected abstract void save(List<String> rows);
    protected void afterImport(int count) {}
}

JDK examples include AbstractList (implement get and size, inherit everything else) and InputStream.read(byte[]), which is built on the single abstract read(). When the steps are simple, passing them as lambdas to one method (a strategy) is often lighter than subclassing.

State

Intent: let an object change its behavior when its internal state changes, as if it changed its class.

Code that checks a status field in every method (if (status == PAID) ... else if (status == SHIPPED) ...) gets messy as states and actions multiply. The State pattern moves each state's behavior into its own object, and transitions become "replace the current state object." In Java, an enum with constant-specific methods is a compact, safe way to write it (see Enums):

Java State: an order lifecycle as an enum state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Every allowed transition is visible in one place, illegal ones fail loudly, and adding a state like RETURNED means adding one constant and the transitions into it. When states need their own data (a Shipped state holding a tracking number), use a sealed interface of records instead of an enum, and compute transitions with a pattern-matching switch.

Patterns and lambdas: a summary

Pattern Classic shape Modern Java shortcut
Strategy Interface + one class per algorithm Lambda or method reference (Comparator.comparing(...))
Command Interface + one class per action Runnable, Callable, Supplier lambdas (unless you need undo)
Observer Listener interface + registration Consumer<Event> listeners; Flow for reactive streams
Template method Abstract class + overrides Pass the varying steps as lambdas
Decorator Wrapper classes Function.andThen / compose for function pipelines
Factory method Overridden creator method Supplier<T> / constructor reference
Iterator Iterator class Iterable + for-each, or streams
Composite / State Class hierarchies Sealed interfaces, records, enums and exhaustive switch

Lambdas don't replace patterns; they are patterns with less ceremony. Name them anyway: a field called discountStrategy tells readers instantly what's going on.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You wrap a repository so every call is logged, and wrap that so results are cached. Both wrappers implement the repository interface. Which pattern is this?

    Decorators keep the same interface, wrap another instance and add behavior, and can be stacked in any order.
  2. 2. With ExchangeRates rates = new LoggingRates(new CachingRates(remote));, you request the same rate three times. How many log lines and remote calls are there?

    The logging decorator is outermost, so it sees every call. The cache inside it answers repeated requests, so the remote service is called once.
  3. 3. A third-party class has getTempF() but your code needs TemperatureSensor.celsius(). What do you write?

    An adapter translates one interface into another without modifying either the vendor class or your interface.
  4. 4. In the command-based editor, why is the redo stack cleared when a new command runs?

    Redo history only makes sense directly after undos. A new action starts a new branch of history, so the old redo entries no longer apply.
  5. 5. Which JDK type is the most familiar example of the Strategy pattern?

    A Comparator encapsulates a comparison algorithm that sort methods accept as a parameter, so the sorting rule can be swapped at run time.

Summary

  • Adapter translates an incompatible interface; Decorator adds behavior by wrapping with the same interface (stackable); Proxy controls access (lazy creation, permissions, remote calls); Facade simplifies a subsystem; Composite treats trees and leaves uniformly.
  • Strategy makes algorithms interchangeable (often lambdas, like Comparator); Observer notifies registered listeners (unsubscribe to avoid leaks); Command turns actions into objects for queues, logs and undo.
  • Iterator hides traversal behind Iterable; Template method fixes an algorithm's skeleton while subclasses fill in steps; State moves state-specific behavior into state objects, neatly expressed with enums or sealed types.
  • Many patterns become one-liners with lambdas, records and sealed types, but naming them still helps readers.

Next: Unit Testing with JUnit, where you'll write automated tests that prove your classes, and the patterns inside them, keep working as the code changes.