Design Patterns in Java with Real Examples

In enterprise software engineering, building extensible, maintainable, and loosely coupled object-oriented systems requires proven architectural blueprints. Design patterns represent tested solutions to recurring design problems encountered while developing Java applications.

By standardizing how classes and objects collaborate, design patterns prevent code duplication and reduce refactoring friction. This comprehensive guide explores four core design patterns every Java developer must master: Singleton (Creational), Factory Method (Creational), Adapter (Structural), and Observer (Behavioral).

1. Singleton Pattern: Thread-Safe Lazy Initialization

The Singleton pattern ensures that a class has only one instance and provides a global access point to it. In enterprise Java, thread safety during concurrent initialization is critical.

C
// Thread-safe Singleton using Bill Pugh Solution (Initialization-on-demand holder idiom)
public class DatabaseConnectionPool {
    
    private DatabaseConnectionPool() {
        // Private constructor prevents external instantiation
    }
    
    private static class Holder {
        private static final DatabaseConnectionPool INSTANCE = new DatabaseConnectionPool();
    }
    
    public static DatabaseConnectionPool getInstance() {
        return Holder.INSTANCE;
    }
    
    public void connect() {
        System.out.println("Connected to database pool successfully.");
    }
}

2. Factory Method Pattern: Decoupling Object Creation

The Factory Method pattern defines an interface for creating an object, but allows subclasses or factory classes to decide which concrete class to instantiate.

C
// Product Interface
public interface Logger {
    void log(String message);
}

// Concrete Products
public class ConsoleLogger implements Logger {
    public void log(String message) {
        System.out.println("[Console Log]: " + message);
    }
}

public class FileLogger implements Logger {
    public void log(String message) {
        System.out.println("[File Log]: " + message);
    }
}

// Factory Class
public class LoggerFactory {
    public static Logger getLogger(String type) {
        if (type.equalsIgnoreCase("CONSOLE")) {
            return new ConsoleLogger();
        } else if (type.equalsIgnoreCase("FILE")) {
            return new FileLogger();
        }
        throw new IllegalArgumentException("Unknown logger type");
    }
}

3. Adapter Pattern: Bridging Incompatible Interfaces

The Adapter pattern allows incompatible classes to work together by wrapping an existing class with a new interface expected by the client.

C
// Target Interface
public interface PaymentGateway {
    void processPayment(double amount);
}

// Legacy Incompatible Service
public class LegacyPayPalService {
    public void makePayment(double totalInUSD) {
        System.out.println("Processing $ " + totalInUSD + " via Legacy PayPal.");
    }
}

// Adapter Class
public class PayPalAdapter implements PaymentGateway {
    private final LegacyPayPalService legacyPayPal;

    public PayPalAdapter(LegacyPayPalService legacyPayPal) {
        this.legacyPayPal = legacyPayPal;
    }

    @Override
    public void processPayment(double amount) {
        legacyPayPal.makePayment(amount);
    }
}

4. Observer Pattern: Event-Driven Notifications

The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified automatically.

C
import java.util.ArrayList;
import java.util.List;

public interface Observer {
    void update(String status);
}

public class Order {
    private final List<Observer> observers = new ArrayList<>();
    private String status;

    public void attach(Observer observer) {
        observers.add(observer);
    }

    public void setStatus(String status) {
        this.status = status;
        notifyObservers();
    }

    private void notifyObservers() {
        for (Observer obs : observers) {
            obs.update(status);
        }
    }
}

public class EmailNotifier implements Observer {
    @Override
    public void update(String status) {
        System.out.println("Email Notification: Order status updated to -> " + status);
    }
}

Conclusion

Applying design patterns in Java—such as thread-safe Singletons, decoupled Factories, flexible Adapters, and event-driven Observers—enables developers to construct resilient, modular, and enterprise-grade software architectures.