Fundamentals 21 min read

Master 7 Essential Design Patterns in Java with Real‑World Code Samples

This article walks through seven core design patterns—Singleton, Factory, Builder, Strategy, Observer, Proxy, and Template Method—explaining their purpose, providing complete Java implementations, and showing how they are applied in JDK and Spring contexts.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Master 7 Essential Design Patterns in Java with Real‑World Code Samples

Design patterns are pervasive in everyday software development, helping developers write scalable and readable code. This guide presents seven of the most commonly used patterns with practical Java examples and discusses their real‑world applications.

1. Singleton Pattern

The Singleton ensures a class has only one instance, ideal for shared resources such as configuration, caches, or thread pools.

public class Singleton {
    private static volatile Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

Key points: volatile guarantees visibility and prevents instruction reordering, while double‑checked locking avoids synchronization overhead after initialization.

Java‑specific uses include java.lang.Runtime.getRuntime() and javax.xml.parsers.DocumentBuilderFactory.newInstance(). In Spring, beans are singleton by default.

2. Factory Pattern

The Factory encapsulates object creation, reducing coupling when constructors become complex.

abstract class Vehicle { abstract void drive(); }
class Car extends Vehicle { public void drive() { System.out.println("Driving a car."); } }
class VehicleFactory {
    public static Vehicle createVehicle(String type) {
        switch (type) {
            case "car": return new Car();
            case "bicycle": return new Bicycle();
            case "truck": return new Truck();
            default: throw new IllegalArgumentException("Invalid vehicle type: " + type);
        }
    }
}

Advantages: decoupled creation logic, easy extension (e.g., adding Motorcycle), and Spring’s BeanFactory and ApplicationContext are classic factory implementations.

3. Builder Pattern

Builder constructs complex objects with many optional parameters, such as a computer configuration.

class Computer {
    private String cpu, memory, storage, graphicsCard, os;
    private Computer(Builder b) { /* assign fields */ }
    public static class Builder {
        private String cpu, memory;
        public Builder(String cpu, String memory) { this.cpu = cpu; this.memory = memory; }
        public Builder storage(String s) { this.storage = s; return this; }
        public Builder graphicsCard(String g) { this.graphicsCard = g; return this; }
        public Builder os(String o) { this.os = o; return this; }
        public Computer build() { return new Computer(this); }
    }
}

Usage:

new Computer.Builder("Intel i7", "16GB").storage("1TB SSD").graphicsCard("RTX 4060").os("Windows 10").build();

4. Strategy Pattern

Strategy encapsulates interchangeable algorithms; the example selects travel methods based on cost and speed.

interface TravelStrategy { void travel(); double calculateCost(double d); double calculateTime(double d); }
class WalkStrategy implements TravelStrategy { /* implementations */ }
class TravelPlanner { private TravelStrategy strategy; public TravelPlanner(TravelStrategy s){ this.strategy = s; } /* setters and delegations */ }

Benefits: easy extension, runtime switching, and clear separation of concerns. JDK’s java.util.Comparator is a classic strategy.

5. Observer Pattern

Observer defines a one‑to‑many dependency; when the subject changes, all observers are notified.

interface StockObserver { void update(double price); }
class Stock implements StockSubject { /* register, remove, notify, setPrice */ }
class Investor implements StockObserver { private String name; public void update(double price){ System.out.println(name+" received an update: " + price); } }

Typical JDK implementations: java.util.Observer/Observable. Spring’s ApplicationEvent and ApplicationListener follow the same principle.

6. Proxy Pattern

Proxy controls access to a target object. Both static and dynamic proxies are shown.

// Static proxy example
interface Service { void execute(); }
class RealService implements Service { public void execute(){ System.out.println("RealService is executing..."); } }
class ServiceProxy implements Service { private Service real = new RealService(); public void execute(){ System.out.println("Before"); real.execute(); System.out.println("After"); } }

Dynamic proxy uses InvocationHandler and Proxy.newProxyInstance to add pre‑ and post‑logic without a concrete proxy class.

Spring AOP is a real‑world dynamic‑proxy application, weaving aspects such as logging or transaction management into beans.

7. Template Method Pattern

Template Method defines the skeleton of an algorithm, delegating specific steps to subclasses.

abstract class BeverageMaker { final void makeBeverage(){ prepare(); brew(); pourInCup(); addCondiments(); } abstract void prepare(); abstract void brew(); void pourInCup(){ System.out.println("Pour the beverage into a cup"); } abstract void addCondiments(); }
class CoffeeMaker extends BeverageMaker { /* implement abstract steps */ }
class TeaMaker extends BeverageMaker { /* implement abstract steps */ }

JDK’s AbstractList and AbstractMap are template‑method bases; Spring’s JdbcTemplate and RestTemplate follow the same pattern.

Overall, these patterns illustrate how to structure code for flexibility, reuse, and maintainability across plain Java and Spring ecosystems.

design-patternsproxyTemplate MethodSingletonStrategyFactoryObserverBuilder
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.