Skip to content
Happy Programming Guide
Start learning
Java

Java Design Patterns

The patterns still worth knowing in modern Java — builder, strategy, factory, observer, decorator and singleton — and which the language has absorbed.

Chess pieces set up on a board

A design pattern is a named solution to a problem that keeps recurring. Java has absorbed several of the classic twenty-three into the language and standard library, so knowing which still need writing is more useful than memorising all of them. This guide covers six that earn their place, with modern Java syntax.

Builder#

The problem: a constructor with eight parameters, half of them optional.

JAVA
// Unreadable at the call site
new Pizza(12, true, false, true, false, true, "thin", 2);
JAVA
public final class Pizza {
    private final int size;
    private final String base;
    private final List<String> toppings;

    private Pizza(Builder builder) {
        this.size = builder.size;
        this.base = builder.base;
        this.toppings = List.copyOf(builder.toppings);
    }

    public static Builder builder(int size) {
        return new Builder(size);
    }

    public static final class Builder {
        private final int size;
        private String base = "classic";
        private final List<String> toppings = new ArrayList<>();

        private Builder(int size) {
            if (size < 6 || size > 18) {
                throw new IllegalArgumentException("size must be 6-18 inches");
            }
            this.size = size;
        }

        public Builder base(String base) {
            this.base = base;
            return this;
        }

        public Builder topping(String topping) {
            this.toppings.add(topping);
            return this;
        }

        public Pizza build() {
            return new Pizza(this);
        }
    }
}
JAVA
Pizza pizza = Pizza.builder(12)
    .base("thin")
    .topping("mushroom")
    .topping("olive")
    .build();

Each value is named at the call site, optional things stay optional, and the result is immutable. This is the pattern with the highest return on effort in Java.

Strategy#

JAVA
public interface DiscountPolicy {
    BigDecimal apply(BigDecimal price);
}

public class Checkout {
    private final DiscountPolicy policy;

    public Checkout(DiscountPolicy policy) {
        this.policy = policy;
    }

    public BigDecimal total(List<BigDecimal> prices) {
        return prices.stream().map(policy::apply)
                     .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}

Because the interface has one method, a lambda satisfies it — no class needed:

JAVA
var checkout = new Checkout(price -> price.multiply(new BigDecimal("0.9")));
var none = new Checkout(price -> price);

Or skip the custom interface entirely and take a UnaryOperator. Strategy in modern Java is often just “accept a function”.

Factory#

JAVA
public interface Exporter {
    String export(List<Order> orders);
}

public final class ExporterFactory {
    private static final Map<String, Supplier<Exporter>> REGISTRY = Map.of(
        "csv",  CsvExporter::new,
        "json", JsonExporter::new
    );

    public static Exporter create(String format) {
        var supplier = REGISTRY.get(format.toLowerCase(Locale.ROOT));
        if (supplier == null) {
            throw new IllegalArgumentException("Unknown format: " + format);
        }
        return supplier.get();
    }
}

A map of constructor references is cleaner than a switch, and adding a format is one line. Use a factory when the type is chosen at run time from data; when it is known at compile time, plain construction is simpler.

A static factory method on the class itself is often enough:

JAVA
public static Temperature ofCelsius(double value) { }
public static Temperature ofFahrenheit(double value) { }

Two constructors with the same signature are impossible; two named methods are clearer anyway.

Singleton#

JAVA
// Do not hand-write this
public class Config {
    private static Config instance;

    public static Config getInstance() {
        if (instance == null) instance = new Config();   // not thread-safe
        return instance;
    }
}

The correct Java singleton is an enum. The language guarantees one instance, thread-safe initialisation, and protection against reflection and serialisation attacks:

JAVA
public enum Config {
    INSTANCE;

    private final Properties properties = load();

    public String get(String key) {
        return properties.getProperty(key);
    }
}

String host = Config.INSTANCE.get("db.host");

Observer#

JAVA
public interface OrderListener {
    void onPlaced(Order order);
}

public class OrderService {
    private final List<OrderListener> listeners = new CopyOnWriteArrayList<>();

    public void addListener(OrderListener listener) {
        listeners.add(listener);
    }

    public void place(Order order) {
        repository.save(order);
        listeners.forEach(l -> l.onPlaced(order));
    }
}
JAVA
service.addListener(order -> sendConfirmation(order));
service.addListener(order -> updateStock(order));

CopyOnWriteArrayList rather than ArrayList matters: listeners are read constantly and written rarely, and a plain list would throw if something subscribed while an event was being dispatched.

For anything crossing a process boundary, a message queue is the right version of this idea.

Decorator#

JAVA
public class CachingProductService implements ProductService {
    private final ProductService inner;
    private final Map<Long, Product> cache = new ConcurrentHashMap<>();

    public CachingProductService(ProductService inner) {
        this.inner = inner;
    }

    @Override
    public Optional<Product> find(long id) {
        var cached = cache.get(id);
        if (cached != null) return Optional.of(cached);

        var result = inner.find(id);
        result.ifPresent(p -> cache.put(id, p));
        return result;
    }
}

Caching, logging, retries and metrics all fit this shape, and they stack — a logging decorator wrapping a caching decorator wrapping the real service. The core class stays unaware of all of it.

Java’s own I/O library is built this way:

JAVA
var reader = new BufferedReader(new InputStreamReader(inputStream));

Patterns Java has absorbed#

Pattern Use instead
Iterator Iterable and the enhanced for loop
Command Runnable, Function, a lambda
Template method pass a function as a parameter
Value object record
Null object Optional
Strategy with one method a lambda
Singleton an enum, or a Spring bean

When a pattern is the wrong answer#

Patterns respond to a problem you already have. Three questions before reaching for one:

  • Is the thing I am abstracting actually going to vary? An interface with one implementation that never gains a second is pure overhead.
  • Would a plain method do? Most single-method interfaces are functions in disguise.
  • Can I name the problem? “I need to swap the discount rule per customer type” justifies strategy. “It seemed more professional” does not.

Questions people ask#

Do I need to learn all twenty-three?

No. Knowing the names helps you read other people’s code and discuss designs. In modern Java perhaps six or seven see regular use, and several of the rest are language features now.

Is dependency injection a pattern?

It is a form of inversion of control — a class receives its collaborators rather than creating them. It underpins most of the patterns here, and Spring is built on it.

Should I use Lombok for builders?

It removes a lot of typing, at the cost of generating code your IDE and tooling must understand. Teams that use it are generally happy; teams that avoid it point at debugging and build complexity. Both positions are defensible.

When has a design become over-engineered?

When explaining it takes longer than the code it replaces, or when adding a feature means editing five files. Both are signs the abstraction is not paying for itself.

Where to go next#

Spring, and the injection these patterns assumeRead next

Keep reading

Java

Java: Where to Go From Here

A recap of what Java covers, an honest self-assessment checklist, the three directions to specialise in, and how to keep learning after…

4 min read

Java

Introduction to Java

What Java is, how the JVM works, where it is used, and your first program — plus an honest comparison with Python,…

5 min read

Java

Java Testing

Unit tests with JUnit 5: assertions, parameterised tests, mocking with Mockito, Spring Boot slice tests, and what is actually worth testing.

5 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *