Design patterns in modern Java
A design pattern is a named, reusable shape for solving a common design problem. Lambdas, records, enums, sealed types and pattern matching make many patterns much shorter in modern Java than in older textbooks, and replace a few altogether. This page explains where the patterns come from and where the JDK itself uses them, implements the ones you will meet most often, shows sealed types replacing the visitor, and runs the traps that break a hand-written singleton.
Contents
What design patterns are, and what modern Java changed Behavioral patterns: strategy, observer, template method Creational patterns: builder, factory method, singleton Structural patterns: decorator and adapter State and command Sealed types instead of the visitor Singleton traps: serialization and reflection Choosing a pattern
What design patterns are, and what modern Java changed
The classic catalogue is the 1994 book Design Patterns by Gamma, Helm, Johnson and Vlissides, the "Gang of Four". It names 23 recurring solutions and groups them by purpose: creational patterns control how objects are made, structural patterns combine objects, and behavioral patterns distribute responsibility between them. The value of a name is communication: "this is a decorator" tells a reader how the class is meant to be used.
Many of those patterns exist because 1990s languages lacked features that Java now has. A strategy or a command is often just a lambda (Java 8). A value object is a record (Java 16). A fixed set of states or a singleton is an enum (Java 5). And a sealed interface with pattern matching in switch
| Pattern | Group | Modern Java form | In the JDK |
|---|---|---|---|
| Strategy | Behavioral | A functional interface and lambdas | Comparatorsort |
| Observer | Behavioral | A list of Consumer | Listeners in Swing; java.util.Observer |
| Template method | Behavioral | A final method calling abstract or lambda-supplied steps | AbstractListgetsize |
| Command | Behavioral | A Runnableundo | RunnableCallable |
| State | Behavioral | An enum with per-constant behaviour | Thread.State |
| Visitor | Behavioral | Sealed types and an exhaustive switch | FileVisitorFiles.walkFileTree |
| Builder | Creational | A static nested builder; a record for small cases | HttpRequest.newBuilder()StringBuilder |
| Factory method | Creational | A static method returning an interface type | List.ofExecutors.newFixedThreadPool |
| Singleton | Creational | An enum with one constant | Runtime.getRuntime() |
| Decorator | Structural | A wrapper implementing the same interface | BufferedInputStreamCollections.unmodifiableList |
| Adapter | Structural | A class or lambda translating one interface to another | Arrays.asListInputStreamReader |
| Proxy | Structural | java.lang.reflect.Proxy | RMI stubs; see |
Each program below was run on JDK 21.
Behavioral patterns: strategy, observer, template method
Shipping cost is the textbook strategy: the same question, "how much for 4 kg?", answered by interchangeable rules. An order event with two listeners shows the observer, and a CSV exporter the template method.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.DoubleUnaryOperator;
public class Behavioral {
// STRATEGY: interchangeable algorithms behind one interface (here, a function)
static final Map<String, DoubleUnaryOperator> SHIPPING = Map.of(
"standard", w -> 5 + w * 0.5,
"express", w -> 15 + w * 1.2,
"pickup", w -> 0);
// OBSERVER: subscribers are notified when something happens
static class OrderEvents {
private final List<Consumer<String>> listeners = new ArrayList<>();
void subscribe(Consumer<String> listener) {
listeners.add(listener);
}
void placed(String orderId) {
listeners.forEach(l -> l.accept(orderId));
}
}
// TEMPLATE METHOD: fixed algorithm, variable steps
abstract static class Exporter {
final String export(List<String> rows) {
return header() + String.join(separator(), rows);
}
abstract String header();
abstract String separator();
}
public static void main(String[] args) {
double weight = 4;
for (String option : List.of("pickup", "standard", "express")) {
double cost = SHIPPING.get(option).applyAsDouble(weight);
System.out.printf("strategy %-8s -> %.2f%n", option, cost);
}
OrderEvents events = new OrderEvents();
events.subscribe(id -> System.out.println("observer email: receipt for " + id));
events.subscribe(id -> System.out.println("observer stock: reserve items for " + id));
events.placed("ORD-17");
Exporter csv = new Exporter() {
@Override
String header() {
return "name\n";
}
@Override
String separator() {
return "\n";
}
};
System.out.println("template method:\n" + csv.export(List.of("ann", "bob")));
}
}
Output:
strategy pickup -> 0.00
strategy standard -> 7.00
strategy express -> 19.80
observer email: receipt for ORD-17
observer stock: reserve items for ORD-17
template method:
name
ann
bob
- Strategy: each shipping rule is a
in a map. For 4 kg, standard costs 5 + 4 × 0.5 = 7.00 and express 15 + 4 × 1.2 = 19.80. Adding a rule means adding a map entry, with no new class and noDoubleUnaryOperator chain.if - Observer: the event source knows only a list of
listeners, and both were notified in subscription order. In real code, think about what happens when a listener throws or is slow, and whether listeners must be removed to avoid leaks.Consumer<String> - Template method:
isexport and fixes the algorithm, header then rows; subclasses fill in only the steps. Since Java 8, passing the steps as lambdas to a constructor is often simpler than subclassing.final
Creational patterns: builder, factory method, singleton
An HTTP request with one required and several optional parts is where a builder pays off. A parser chosen by file format shows a factory method, and an enum the safe singleton.
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Creational {
// BUILDER: readable construction of an object with many optional parts
static final class HttpRequest {
private final String url;
private final String method;
private final List<String> headers;
private final int timeoutSeconds;
private HttpRequest(Builder b) {
this.url = Objects.requireNonNull(b.url, "url is required");
this.method = b.method;
this.headers = List.copyOf(b.headers);
this.timeoutSeconds = b.timeoutSeconds;
}
static Builder builder(String url) {
return new Builder(url);
}
@Override
public String toString() {
return method + " " + url + " " + headers + " timeout=" + timeoutSeconds + "s";
}
static final class Builder {
private final String url;
private String method = "GET";
private final List<String> headers = new ArrayList<>();
private int timeoutSeconds = 30;
private Builder(String url) {
this.url = url;
}
Builder method(String m) {
this.method = m;
return this;
}
Builder header(String h) {
headers.add(h);
return this;
}
Builder timeout(int s) {
this.timeoutSeconds = s;
return this;
}
HttpRequest build() {
return new HttpRequest(this);
}
}
}
// FACTORY METHOD: callers ask for "a parser for this format", not a concrete class
sealed interface Parser permits CsvParser, TsvParser {
List<String> parse(String line);
static Parser forFormat(String format) {
return switch (format) {
case "csv" -> new CsvParser();
case "tsv" -> new TsvParser();
default -> throw new IllegalArgumentException("unknown format " + format);
};
}
}
record CsvParser() implements Parser {
@Override
public List<String> parse(String line) {
return List.of(line.split(","));
}
}
record TsvParser() implements Parser {
@Override
public List<String> parse(String line) {
return List.of(line.split("\t"));
}
}
// SINGLETON: the enum form is thread-safe and serialization-safe
enum Registry {
INSTANCE;
private int lookups;
int lookup() {
return ++lookups;
}
}
public static void main(String[] args) {
HttpRequest req = HttpRequest.builder("https://api.example.com/orders")
.method("POST").header("Accept: application/json").timeout(5).build();
System.out.println("builder: " + req);
Parser parser = Parser.forFormat("csv");
System.out.println("factory: " + parser.parse("a,b,c")
+ " via " + parser.getClass().getSimpleName());
Registry.INSTANCE.lookup();
int count = Registry.INSTANCE.lookup();
boolean same = Registry.INSTANCE == Registry.valueOf("INSTANCE");
System.out.println("singleton: " + count + " lookups, same instance: " + same);
}
}
Output:
builder: POST https://api.example.com/orders [Accept: application/json] timeout=5s
factory: [a, b, c] via CsvParser
singleton: 2 lookups, same instance: true
- Builder: named methods replace a constructor with many parameters of the same type, where swapping two arguments compiles silently. The URL is required by the
method, the others have defaults, and the final object is immutable, withbuilder taking a snapshot of the headers.List.copyOf - Factory method: callers ask for "a parser for csv" and get a
, not aParser , so implementations can change without touching callers. The sealed interface lists all implementations, so aCsvParser over parsers elsewhere can be checked for completeness.switch - Singleton: the enum's one constant is created when the enum class is initialized, which the JVM does once and thread-safely. The two lookups used the same instance. The next-but-one section shows why a hand-written singleton class is weaker.
Structural patterns: decorator and adapter
A notifier interface gets two decorators that add behaviour, and an adapter that makes an old SMS class fit the same interface.
public class Structural {
interface Notifier {
String send(String msg);
}
static class EmailNotifier implements Notifier {
@Override
public String send(String msg) {
return "email(" + msg + ")";
}
}
// DECORATOR: wraps an object of the same interface and adds behavior
static class Timestamped implements Notifier {
private final Notifier inner;
Timestamped(Notifier inner) {
this.inner = inner;
}
@Override
public String send(String msg) {
return inner.send("[09:00] " + msg);
}
}
static class Uppercased implements Notifier {
private final Notifier inner;
Uppercased(Notifier inner) {
this.inner = inner;
}
@Override
public String send(String msg) {
return inner.send(msg.toUpperCase());
}
}
// ADAPTER: makes an existing class fit an interface it was not written for
static class LegacySms {
void transmit(String number, String text) {
System.out.println(" legacy SMS to " + number + ": " + text);
}
}
static class SmsAdapter implements Notifier {
private final LegacySms sms = new LegacySms();
@Override
public String send(String msg) {
sms.transmit("+1-555-0100", msg);
return "sms(" + msg + ")";
}
}
public static void main(String[] args) {
Notifier plain = new EmailNotifier();
Notifier decorated = new Uppercased(new Timestamped(new EmailNotifier()));
System.out.println("plain: " + plain.send("build passed"));
System.out.println("decorated: " + decorated.send("build passed"));
System.out.println("adapted: " + new SmsAdapter().send("deploy done"));
}
}
Output:
plain: email(build passed)
decorated: email([09:00] BUILD PASSED)
legacy SMS to +1-555-0100: deploy done
adapted: sms(deploy done)
- Decorators implement the same interface as the object they wrap and add behaviour before or after delegating. The outer
ran first, thenUppercased added the prefix, so the order of wrapping decides the result: "[09:00] BUILD PASSED". Java's I/O streams are built the same way: aTimestamped around anBufferedReader around aInputStreamReader .FileInputStream - The adapter translated
into the legacy class'ssend(msg) . Neither the caller nor the legacy code had to change, which is the whole purpose.transmit(number, text) - Decorators and adapters look alike in code. The difference is intent: a decorator keeps the interface and adds behaviour; an adapter changes the interface and keeps the behaviour.
State and command
An order that can be paid, shipped or cancelled receives events, some of which are not allowed in its current state. A tiny text editor then records each change as a command so it can be undone.
import java.util.ArrayDeque;
import java.util.Deque;
public class StateAndCommand {
// STATE: behaviour depends on the current state; each enum constant is one state
enum Order {
NEW {
Order next(String event) {
return event.equals("pay") ? PAID : event.equals("cancel") ? CANCELLED : this;
}
},
PAID {
Order next(String event) {
return event.equals("ship") ? SHIPPED : this;
}
},
SHIPPED {
Order next(String event) {
return this;
}
},
CANCELLED {
Order next(String event) {
return this;
}
};
abstract Order next(String event);
}
// COMMAND: an action as an object, so it can be queued, logged or undone
interface Command {
void run();
void undo();
}
static final StringBuilder DOC = new StringBuilder();
static Command append(String text) {
return new Command() {
public void run() {
DOC.append(text);
}
public void undo() {
DOC.setLength(DOC.length() - text.length());
}
};
}
public static void main(String[] args) {
Order state = Order.NEW;
for (String event : new String[] {"ship", "pay", "cancel", "ship", "pay"}) {
Order before = state;
state = state.next(event);
System.out.printf("state: %-9s + %-6s -> %s%n", before, event, state);
}
Deque<Command> history = new ArrayDeque<>();
for (String word : new String[] {"Hello", ", ", "world", "!!!"}) {
Command c = append(word);
c.run();
history.push(c);
}
System.out.println("command: after 4 appends: " + DOC);
history.pop().undo();
history.pop().undo();
System.out.println("command: after 2 undos: " + DOC);
}
}
Output:
state: NEW + ship -> NEW
state: NEW + pay -> PAID
state: PAID + cancel -> PAID
state: PAID + ship -> SHIPPED
state: SHIPPED + pay -> SHIPPED
command: after 4 appends: Hello, world!!!
command: after 2 undos: Hello,
- State: each enum constant implements
for its own state. "ship" on anext order was ignored, "pay" moved it toNEW , "cancel" after payment was ignored, andPAID accepts nothing further. All transitions live in one place, instead ofSHIPPED checks scattered through the code.if (status == ...) - Command: each append is an object that knows how to do and undo itself. Keeping them on a stack gave undo for free: two undos removed "!!!" and "world", leaving "Hello, ". The same idea underlies task queues, where commands are
s submitted to an executor.Runnable
Sealed types instead of the visitor
The visitor pattern lets you add operations to a fixed set of types without changing them, at the price of an acceptswitch
import java.util.List;
public class SealedVisitor {
// Classic VISITOR: one visit method per element type, and accept() in every element
interface ShapeVisitor<R> {
R visitCircle(Circle c);
R visitRect(Rect r);
}
interface Shape {
<R> R accept(ShapeVisitor<R> v);
}
record Circle(double r) implements Shape {
public <R> R accept(ShapeVisitor<R> v) {
return v.visitCircle(this);
}
}
record Rect(double w, double h) implements Shape {
public <R> R accept(ShapeVisitor<R> v) {
return v.visitRect(this);
}
}
static final class AreaVisitor implements ShapeVisitor<Double> {
public Double visitCircle(Circle c) {
return Math.PI * c.r() * c.r();
}
public Double visitRect(Rect r) {
return r.w() * r.h();
}
}
// Java 21: a sealed hierarchy plus a pattern-matching switch does the same job
sealed interface Shape2 permits Circle2, Rect2, Square2 { }
record Circle2(double r) implements Shape2 { }
record Rect2(double w, double h) implements Shape2 { }
record Square2(double side) implements Shape2 { }
static double area(Shape2 s) {
return switch (s) { // exhaustive: no default needed
case Circle2 c -> Math.PI * c.r() * c.r();
case Rect2(double w, double h) -> w * h;
case Square2(double side) -> side * side;
};
}
public static void main(String[] args) {
List<Shape> old = List.of(new Circle(1), new Rect(2, 3));
AreaVisitor av = new AreaVisitor();
for (Shape s : old) {
System.out.printf("visitor: %-24s area %.2f%n", s, s.accept(av));
}
List<Shape2> modern = List.of(new Circle2(1), new Rect2(2, 3), new Square2(2));
for (Shape2 s : modern) {
System.out.printf("switch: %-24s area %.2f%n", s, area(s));
}
}
}
Output:
visitor: Circle[r=1.0] area 3.14
visitor: Rect[w=2.0, h=3.0] area 6.00
switch: Circle2[r=1.0] area 3.14
switch: Rect2[w=2.0, h=3.0] area 6.00
switch: Square2[side=2.0] area 4.00
- Both produced the same areas: 3.14 for the unit circle and 6.00 for the 2 by 3 rectangle.
- The visitor needed an interface method per type and an
method in every record. Addingaccept would have meant changing the visitor interface and every visitor.Square - The
over the sealedswitch has noShape2 . Because the compiler knows all permitted subtypes, it checks that every one is handled; addingdefault without a case would be a compile error, exactly the guarantee the visitor was invented for. Record patterns such asSquare2 take the fields apart in the same step. SeeRect2(double w, double h)sealed classes with pattern matching .
Singleton traps: serialization and reflection
A hand-written singleton relies on a private constructor and a static field. Two Java mechanisms can create objects without going through that design, and the program tries both on three singleton variants.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
public class SingletonTraps {
// A classic singleton: private constructor, static instance
static final class Config implements Serializable {
static final Config INSTANCE = new Config();
private Config() {
}
}
// The same, protected against serialization copies
static final class SafeConfig implements Serializable {
static final SafeConfig INSTANCE = new SafeConfig();
private SafeConfig() {
}
private Object readResolve() {
return INSTANCE; // replace the copy with the real one
}
}
// The enum form: the JVM and serialization guarantee one instance
enum EnumConfig {
INSTANCE
}
@SuppressWarnings("unchecked")
static <T> T roundTrip(T obj) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(obj);
}
try (ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bytes.toByteArray()))) {
return (T) in.readObject();
}
}
public static void main(String[] args) throws Exception {
// Trap 1: deserialization creates a second instance
System.out.println("1. class singleton after serialization, same object: "
+ (roundTrip(Config.INSTANCE) == Config.INSTANCE));
System.out.println(" with readResolve: "
+ (roundTrip(SafeConfig.INSTANCE) == SafeConfig.INSTANCE));
System.out.println(" enum: "
+ (roundTrip(EnumConfig.INSTANCE) == EnumConfig.INSTANCE));
// Trap 2: reflection can call the private constructor
Constructor<Config> c = Config.class.getDeclaredConstructor();
c.setAccessible(true);
System.out.println("2. reflection made another Config: "
+ (c.newInstance() != Config.INSTANCE));
Constructor<?> e = EnumConfig.class.getDeclaredConstructors()[0];
e.setAccessible(true);
try {
e.newInstance("SECOND", 1);
} catch (IllegalArgumentException ex) {
System.out.println(" enum: IllegalArgumentException: " + ex.getMessage());
}
}
}
Output:
1. class singleton after serialization, same object: false
with readResolve: true
enum: true
2. reflection made another Config: true
enum: IllegalArgumentException: Cannot reflectively create enum objects
- Serializing and deserializing the plain singleton produced a second object, because deserialization creates instances without calling the constructor. A
method that returns the real instance fixed it. The enum needed nothing: enum constants are serialized by name and resolved back to the existing constant.readResolve - Reflection with
called the private constructor and made anothersetAccessible(true) . For the enum, the JDK refused: "Cannot reflectively create enum objects".Config
That is why Effective Java recommends a single-element enum for singletons. Often the better question is whether a singleton is needed at all: a single instance passed to the classes that use it, for example by a dependency injection framework, is easier to test and replace.
Choosing a pattern
| Problem | Pattern, in modern Java |
|---|---|
| Several interchangeable algorithms | Strategy: a functional interface and lambdas |
| Notify other parts of the program about events | Observer: a list of Consumer |
| Many optional constructor parameters | Builder |
| Hide which implementation is created | Static factory method returning an interface |
| Add behaviour to an object without subclassing | Decorator |
| Use a class through an interface it does not implement | Adapter |
| Behaviour that depends on a fixed set of states | State: an enum with per-constant methods |
| Actions to queue, log or undo | Command |
| Operations over a fixed set of types | Sealed interface and exhaustive switch |
| Exactly one instance | A single-element enum, or one instance managed by the application |
Patterns are a vocabulary, not a goal: use one when it removes a real problem. See