Back to Study Material Java

Java Design Patterns

Design patterns are reusable solutions to recurring problems in software design. They are not code libraries but rather templates — descriptions of how t...

Java Design Patterns

Creational Patterns in Java

Design patterns are reusable solutions to recurring problems in software design. They are not code libraries but rather templates — descriptions of how to structure classes and their interactions to achieve a specific goal. The creational patterns focus on how objects are created, providing flexibility and decoupling from specific implementations.

The Singleton pattern ensures a class has exactly one instance and provides a global access point to it. The classic implementation uses a private constructor, a private static field holding the single instance, and a public static getInstance() method. In multi-threaded environments, the double-checked locking idiom or the initialization-on-demand holder pattern ensures thread safety without the overhead of synchronizing every call. The enum singleton — a single-element enum — is Joshua Bloch's recommended approach in Effective Java because the JVM guarantees enum instances are created once and protected from serialization and reflection attacks.

The Factory Method pattern defines an interface for creating an object but lets subclasses decide which class to instantiate. A ShapeFactory interface with a createShape() method, implemented by CircleFactory and RectangleFactory, allows client code to work with Shape objects without knowing concrete types. This supports the Open/Closed Principle: adding new shapes requires a new factory class, not changes to existing code.

The Builder pattern is valuable when a class has many optional parameters. Instead of a constructor with a dozen parameters (where passing nulls for unused parameters is error-prone), you provide a fluent Builder class: User user = new User.Builder("Alice", "[email protected]").age(30).phone("555-1234").build(). Each setter method on the builder returns the builder itself, enabling chaining. The final build() call validates the collected parameters and constructs the immutable User. Java's java.lang.StringBuilder and java.time's DateTimeFormatter.Builder are examples from the standard library.

The Abstract Factory pattern provides an interface for creating families of related objects. A UIFactory interface might produce Button, TextField, and Dialog; a WindowsUIFactory creates Windows-styled widgets while a MacUIFactory creates macOS-styled ones. Client code uses the factory interface exclusively and is unaware of which platform-specific family it is working with.

Structural and Behavioral Patterns

Structural patterns address how classes and objects are composed to form larger structures. Behavioral patterns focus on communication between objects and the assignment of responsibilities.

The Decorator pattern attaches additional behavior to an object dynamically by wrapping it in an object of a class that shares its interface. Java's I/O library is built on this pattern. FileInputStream provides raw bytes. BufferedInputStream wraps it to add buffering. DataInputStream wraps that to add typed reads. Each layer adds behavior without modifying the wrapped class. This is far more flexible than subclassing, which would require a new subclass for every combination of behaviors.

The Adapter pattern converts the interface of a class into an interface the client expects. If you have a LegacyPaymentProcessor with a makePayment(double amount, String currency) method but your system expects a PaymentGateway interface with processCharge(Money money), an adapter class implements PaymentGateway, holds a reference to LegacyPaymentProcessor, and translates calls. This is pervasive in integration code that connects systems with incompatible interfaces.

The Observer pattern defines a one-to-many dependency: when one object (the subject) changes state, all dependent objects (observers) are notified and updated automatically. Java's built-in PropertyChangeSupport and event listener frameworks follow this pattern. Modern Java often implements it with the reactive streams API (java.util.concurrent.Flow) or frameworks like RxJava. The pattern is fundamental to event-driven architectures, UI frameworks, and publish-subscribe messaging systems.

The Strategy pattern defines a family of algorithms, encapsulates each one as an object, and makes them interchangeable. A SortingContext that holds a reference to a SortStrategy interface can sort using BubbleSortStrategy, QuickSortStrategy, or MergeSortStrategy interchangeably. Switching the algorithm at runtime is a single setter call. With Java 8 lambdas, simple strategies collapse to passing a lambda: context.setStrategy((a, b) -> a.compareTo(b)).

The Command pattern encapsulates a request as an object, supporting undo operations, request queuing, and logging. Each command object implements an execute() method and optionally an undo() method. This is the foundation of transaction systems and editor undo histories.

Applying Patterns in Real Java Codebases

Knowing pattern names and diagrams is far less valuable than knowing when to apply each pattern and when not to. Misapplied patterns add complexity without benefit — a form of over-engineering called design pattern abuse. The goal is always to solve a real problem, not to demonstrate pattern knowledge.

The most commonly over-applied pattern is Singleton. Because Singleton provides global state, it makes code harder to test (you cannot easily substitute a mock), creates hidden dependencies, and causes problems in multi-instance deployments (like clustered web servers where each JVM has its own Singleton). Modern Java code prefers dependency injection (through frameworks like Spring or Guice) which provides the "one instance per application" behavior of Singleton without the global state problems.

The Strategy pattern should be your first thought when you see a switch or if-else chain that dispatches to different algorithms based on a type flag. Replacing the conditional with a map from type to strategy object makes adding new algorithms a matter of adding a new class and registering it in the map — no changes to existing code.

Repository is a domain-driven design pattern that abstracts the data access layer behind a collection-like interface. Client code calls userRepository.findByEmail(email) without knowing whether the implementation queries a SQL database, calls a REST API, or searches an in-memory list. This makes business logic testable with mock repositories and makes storage technology changes transparent to the service layer.

Template Method defines the skeleton of an algorithm in a base class, deferring specific steps to subclasses. A DataMigrator base class might define the sequence — openSource(), readBatch(), transform(), writeBatch(), close() — with each step as an abstract method. Subclasses implement the steps for specific data formats. The sequence logic lives in one place; the variation lives in subclasses.

One practical tip: when you read source code of well-regarded Java libraries — Spring Framework, Guava, Jackson — look for patterns explicitly. Spring uses Factory, Proxy, Template Method, and Observer extensively; recognizing them in production code teaches you how patterns scale beyond textbook examples.