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

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 (Java 21) replaces most uses of the visitor. The JDK itself is full of patterns:

Patterns, their modern Java form, and examples in the JDK
PatternGroupModern Java formIn the JDK
StrategyBehavioralA functional interface and lambdasComparator passed to sort
ObserverBehavioralA list of Consumer callbacksListeners in Swing; java.util.Observer was deprecated in Java 9
Template methodBehavioralA final method calling abstract or lambda-supplied stepsAbstractList, where you supply get and size
CommandBehavioralA Runnable or a small interface with undoRunnable and Callable submitted to executors
StateBehavioralAn enum with per-constant behaviourThread.State (as data)
VisitorBehavioralSealed types and an exhaustive switchFileVisitor for Files.walkFileTree
BuilderCreationalA static nested builder; a record for small casesHttpRequest.newBuilder(), StringBuilder
Factory methodCreationalA static method returning an interface typeList.of, Executors.newFixedThreadPool
SingletonCreationalAn enum with one constantRuntime.getRuntime()
DecoratorStructuralA wrapper implementing the same interfaceBufferedInputStream, Collections.unmodifiableList
AdapterStructuralA class or lambda translating one interface to anotherArrays.asList, InputStreamReader
ProxyStructuraljava.lang.reflect.ProxyRMI stubs; see dynamic proxies

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.

Java
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:

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 DoubleUnaryOperator 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 no if chain.
  • Observer: the event source knows only a list of Consumer<String> 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.
  • Template method: export is final 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.

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.

Java
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:

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 builder method, the others have defaults, and the final object is immutable, with List.copyOf taking a snapshot of the headers.
  • Factory method: callers ask for "a parser for csv" and get a Parser, not a CsvParser, so implementations can change without touching callers. The sealed interface lists all implementations, so a switch over parsers elsewhere can be checked for completeness.
  • 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.

Java
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:

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 Uppercased ran first, then Timestamped 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: a BufferedReader around an InputStreamReader around a FileInputStream.
  • The adapter translated send(msg) into the legacy class's transmit(number, text). Neither the caller nor the legacy code had to change, which is the whole purpose.
  • 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.

Java
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:

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 next for its own state. "ship" on a NEW order was ignored, "pay" moved it to PAID, "cancel" after payment was ignored, and SHIPPED accepts nothing further. All transitions live in one place, instead of if (status == ...) checks scattered through the code.
  • 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 Runnables submitted to an executor.

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 accept method in every type and a visitor interface listing every type. Java 21's sealed interfaces, record patterns and exhaustive switch give the same safety with far less code. Both versions compute shape areas below; the modern one has an extra shape.

Java
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:

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 accept method in every record. Adding Square would have meant changing the visitor interface and every visitor.
  • The switch over the sealed Shape2 has no default. Because the compiler knows all permitted subtypes, it checks that every one is handled; adding Square2 without a case would be a compile error, exactly the guarantee the visitor was invented for. Record patterns such as Rect2(double w, double h) take the fields apart in the same step. See 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.

Java
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:

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
  1. Serializing and deserializing the plain singleton produced a second object, because deserialization creates instances without calling the constructor. A readResolve 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.
  2. Reflection with setAccessible(true) called the private constructor and made another Config. For the enum, the JDK refused: "Cannot reflectively create enum objects".

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

Which pattern for which problem
ProblemPattern, in modern Java
Several interchangeable algorithmsStrategy: a functional interface and lambdas
Notify other parts of the program about eventsObserver: a list of Consumer callbacks, removable
Many optional constructor parametersBuilder
Hide which implementation is createdStatic factory method returning an interface
Add behaviour to an object without subclassingDecorator
Use a class through an interface it does not implementAdapter
Behaviour that depends on a fixed set of statesState: an enum with per-constant methods
Actions to queue, log or undoCommand
Operations over a fixed set of typesSealed interface and exhaustive switch
Exactly one instanceA 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 functional interfaces for lambda-based strategies, enums and records for the building blocks, and dynamic proxies for the proxy pattern.