What Are Design Patterns in Java and When Should You Use Them?

Learn What Are Design Patterns in Java and When Should You Use Them? with practical examples, explanations, best practices, and real-world coding techniques.

Java design patterns are reusable approaches to common software design problems. A design pattern is not a ready-made library or a piece of code that must be copied exactly. Instead, it provides a proven way to structure classes, objects, responsibilities, and communication so that a particular design problem can be solved more cleanly.

Design patterns become especially useful as Java applications grow. A small program may work perfectly with a few classes and direct object creation, but larger systems often need to handle changing business rules, interchangeable implementations, external dependencies, shared state, event notifications, and complex object construction. Design patterns provide a vocabulary for these recurring design situations.

What a Design Pattern Really Provides

Problem

A recurring design problem appears in the application.

Structure

A reusable arrangement of objects and responsibilities addresses the problem.

Trade-offs

The pattern improves certain qualities while introducing its own complexity and constraints.

Why Learn Design Patterns in Java?

Learning design patterns helps you recognize common design problems instead of solving every problem from scratch. It also gives developers a common vocabulary. Saying that a class uses a Strategy immediately communicates an idea about interchangeable behavior without requiring a long explanation of the entire design.

  • Improve object-oriented design and separation of responsibilities.
  • Reduce unnecessary coupling between classes.
  • Make implementations easier to replace or extend.
  • Improve maintainability when business requirements change.
  • Provide a shared design vocabulary for development teams.
  • Help developers understand the structure of existing enterprise Java applications.

Patterns Are Not Rules

A design pattern should solve a real design problem. Adding patterns merely to make code look "advanced" can make a simple application harder to understand. Good design is about choosing the simplest structure that satisfies the requirements.

The Three Main Categories of Design Patterns

The classic design-pattern classification popularized by the Gang of Four groups patterns into three categories based on the primary problem they address.

Creational

Focus on how objects are created and how object construction can be separated from the rest of the application.

Examples: Factory, Builder, Singleton

Structural

Focus on how classes and objects are composed to create larger and more flexible structures.

Examples: Adapter, Decorator, Facade

Behavioral

Focus on communication, responsibilities, and how objects collaborate.

Examples: Strategy, Observer, Template Method

Creational Design Patterns in Java

Creational patterns address object creation. Instead of allowing object construction logic to spread throughout the application, these patterns can centralize or control how objects are created.

1. Factory Pattern

The Factory Pattern separates object creation from the code that uses the object. The client works with a common interface or abstraction while a factory decides which concrete implementation should be created.

This is useful when the application may create different implementations based on configuration, user input, environment, or business rules.

interface PaymentMethod {
    void pay(double amount);
}

class CardPayment implements PaymentMethod {

    @Override
    public void pay(double amount) {
        System.out.println(
            "Paid ₹" + amount + " using card."
        );
    }
}

class UpiPayment implements PaymentMethod {

    @Override
    public void pay(double amount) {
        System.out.println(
            "Paid ₹" + amount + " using UPI."
        );
    }
}

class PaymentFactory {

    public static PaymentMethod create(
            String type) {

        return switch (type.toLowerCase()) {
            case "card" -> new CardPayment();
            case "upi" -> new UpiPayment();
            default ->
                throw new IllegalArgumentException(
                    "Unsupported payment method"
                );
        };
    }
}

The calling code does not need to know which concrete payment class is instantiated. It only depends on the PaymentMethod abstraction.

2. Builder Pattern

The Builder Pattern is useful for creating objects with many optional values or configurations. Instead of creating constructors with a large number of parameters, the builder provides a readable step-by-step construction API.

class User {

    private final String name;
    private final String email;
    private final String phone;
    private final boolean active;

    private User(Builder builder) {
        this.name = builder.name;
        this.email = builder.email;
        this.phone = builder.phone;
        this.active = builder.active;
    }

    public static class Builder {

        private final String name;
        private final String email;

        private String phone;
        private boolean active;

        public Builder(
                String name,
                String email) {

            this.name = name;
            this.email = email;
        }

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

        public Builder active(boolean active) {
            this.active = active;
            return this;
        }

        public User build() {
            return new User(this);
        }
    }
}
User user =
    new User.Builder(
        "Ananya",
        "ananya@example.com"
    )
    .phone("9876543210")
    .active(true)
    .build();

Builders can improve readability and make it easier to validate object creation before returning the final instance.

3. Singleton Pattern

The Singleton Pattern restricts a class to a single instance within a particular application context and provides a controlled access point to that instance.

Singleton can be useful for certain stateless services, configuration holders, or other genuinely shared resources. However, it should not be used simply because a class is accessed from many places. Global mutable state can make testing and dependency management more difficult.

public final class AppConfig {

    private static final AppConfig INSTANCE =
            new AppConfig();

    private AppConfig() {
    }

    public static AppConfig getInstance() {
        return INSTANCE;
    }
}

In modern Java, an enum can also be an effective way to implement a singleton where the singleton design is genuinely appropriate.

public enum ApplicationConfig {

    INSTANCE;

    public String getEnvironment() {
        return "production";
    }
}

Structural Design Patterns in Java

Structural patterns focus on how classes and objects are connected. They are particularly useful when existing components need to work together without tightly coupling the application to their concrete implementations.

4. Adapter Pattern

The Adapter Pattern allows one interface to be used where another interface is expected. It is useful when integrating legacy code, third-party libraries, or components whose APIs do not match your application's abstraction.

interface NotificationService {
    void send(String message);
}

class LegacySmsClient {

    public void sendSms(String text) {
        System.out.println(
            "SMS sent: " + text
        );
    }
}

class SmsAdapter implements NotificationService {

    private final LegacySmsClient client;

    public SmsAdapter(
            LegacySmsClient client) {

        this.client = client;
    }

    @Override
    public void send(String message) {
        client.sendSms(message);
    }
}

The rest of the application depends on NotificationService rather than directly depending on the legacy client's API.

5. Decorator Pattern

The Decorator Pattern adds behavior to an object dynamically by wrapping it with another object that implements the same abstraction. This can be useful when multiple optional behaviors need to be combined without creating a large inheritance hierarchy.

interface MessageSender {
    void send(String message);
}

class BasicSender implements MessageSender {

    @Override
    public void send(String message) {
        System.out.println(
            "Sending: " + message
        );
    }
}

class LoggingSender implements MessageSender {

    private final MessageSender sender;

    public LoggingSender(
            MessageSender sender) {

        this.sender = sender;
    }

    @Override
    public void send(String message) {

        System.out.println(
            "Log: sending message"
        );

        sender.send(message);
    }
}

6. Facade Pattern

The Facade Pattern provides a simple interface over a more complicated subsystem. The client does not need to know every internal component involved in completing an operation.

class InventoryService {

    public void reserveItem() {
        System.out.println(
            "Inventory reserved"
        );
    }
}

class PaymentService {

    public void charge() {
        System.out.println(
            "Payment processed"
        );
    }
}

class ShippingService {

    public void createShipment() {
        System.out.println(
            "Shipment created"
        );
    }
}

class OrderFacade {

    private final InventoryService inventory;
    private final PaymentService payment;
    private final ShippingService shipping;

    public OrderFacade() {
        inventory = new InventoryService();
        payment = new PaymentService();
        shipping = new ShippingService();
    }

    public void placeOrder() {
        inventory.reserveItem();
        payment.charge();
        shipping.createShipment();
    }
}

The application can call placeOrder() without coordinating every subsystem directly.

Behavioral Design Patterns in Java

Behavioral patterns focus on communication and responsibility between objects. They help define how an application chooses algorithms, distributes responsibilities, responds to events, or processes operations.

7. Strategy Pattern

The Strategy Pattern defines a family of interchangeable algorithms or behaviors. The application can select the required strategy without changing the code that uses it.

interface DiscountStrategy {
    double calculateDiscount(double price);
}

class NoDiscount implements DiscountStrategy {

    @Override
    public double calculateDiscount(
            double price) {

        return 0;
    }
}

class FestivalDiscount
        implements DiscountStrategy {

    @Override
    public double calculateDiscount(
            double price) {

        return price * 0.20;
    }
}

class CheckoutService {

    private final DiscountStrategy strategy;

    public CheckoutService(
            DiscountStrategy strategy) {

        this.strategy = strategy;
    }

    public double calculateFinalPrice(
            double price) {

        return price
                - strategy.calculateDiscount(price);
    }
}

Strategy is especially useful when a system has multiple business rules that vary independently. In Java, lambdas and method references can also provide lightweight strategy implementations when the behavior maps naturally to a functional interface.

8. Observer Pattern

The Observer Pattern establishes a one-to-many relationship in which one object publishes a change or event and multiple interested objects can react to it.

This pattern is useful for notification systems, UI events, application events, monitoring systems, and other event-driven designs.

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

interface Subscriber {
    void onMessage(String message);
}

class NewsPublisher {

    private final List<Subscriber> subscribers =
            new ArrayList<>();

    public void subscribe(Subscriber subscriber) {
        subscribers.add(subscriber);
    }

    public void unsubscribe(
            Subscriber subscriber) {

        subscribers.remove(subscriber);
    }

    public void publish(String message) {

        for (Subscriber subscriber : subscribers) {
            subscriber.onMessage(message);
        }
    }
}

class EmailSubscriber
        implements Subscriber {

    private final String email;

    public EmailSubscriber(String email) {
        this.email = email;
    }

    @Override
    public void onMessage(String message) {

        System.out.println(
            "Sending email to "
            + email
            + ": "
            + message
        );
    }
}

9. Template Method Pattern

The Template Method Pattern defines the overall steps of an algorithm in a base class while allowing subclasses to customize specific steps.

abstract class DataImporter {

    public final void importData() {

        openSource();
        readData();
        validateData();
        saveData();
    }

    protected abstract void openSource();

    protected abstract void readData();

    protected void validateData() {
        System.out.println(
            "Validating data..."
        );
    }

    protected abstract void saveData();
}

The parent class owns the overall workflow, while subclasses provide the details for individual steps.

Common Java Design Patterns at a Glance

Pattern Category Primary Problem
Factory Creational Centralize or abstract object creation
Builder Creational Construct complex objects clearly
Singleton Creational Control a single shared instance
Adapter Structural Make incompatible interfaces work together
Decorator Structural Add behavior without changing the wrapped class
Facade Structural Simplify access to complex subsystems
Strategy Behavioral Make algorithms interchangeable
Observer Behavioral Notify multiple interested objects
Template Method Behavioral Define an algorithm skeleton with customizable steps

Composition vs Inheritance in Design Patterns

Many Java design patterns encourage composition rather than relying heavily on inheritance. Composition means an object contains or uses another object to perform a responsibility.

For example, the Strategy Pattern can inject a discount strategy into a checkout service instead of creating a separate checkout subclass for every discount algorithm.

Inheritance

Behavior is often extended through subclasses. It can work well when there is a stable and genuine "is-a" relationship.

Composition

Behavior is delegated to another object. It often provides greater flexibility because implementations can be changed without changing the owning class hierarchy.

SOLID Principles and Design Patterns

Design patterns are closely related to object-oriented design principles such as SOLID. Patterns do not replace those principles; they are practical structures that can help implement good design in recurring situations.

For example, Strategy can help separate changing algorithms from the class that uses them. Factory can separate object creation from business logic. Adapter can isolate an external API from the rest of the application.

The goal is not to force every SOLID principle or every design pattern into every class. The goal is to keep responsibilities clear and dependencies manageable.

Design Patterns in Real Java Applications

You may already be using design-pattern ideas without explicitly naming them. Java libraries and frameworks frequently rely on abstractions, factories, builders, adapters, observers, proxies, strategies, and other patterns.

For example, an application might use:

  • A factory to select an implementation based on a payment type.
  • A builder to construct a request containing many optional values.
  • An adapter to integrate a third-party payment SDK.
  • A strategy to switch pricing or validation rules.
  • An observer-style event mechanism to publish application events.
  • A facade to provide one simple API over several internal services.

How to Choose the Right Design Pattern

Choosing a design pattern should start with the problem, not with the pattern name. Ask what is changing, what is tightly coupled, and which responsibility should be isolated.

  1. Identify the part of the design that is difficult to change.
  2. Identify the responsibility that should be isolated.
  3. Look for a pattern that matches the actual problem.
  4. Compare the pattern's benefits with its additional complexity.
  5. Keep the implementation as small as the requirement allows.
  6. Test the resulting design and revise it when the requirements evolve.

When Design Patterns Can Hurt

Design patterns are useful abstractions, but overusing them can make code more complicated than the original problem requires. Creating factories, interfaces, wrappers, managers, and multiple layers for a simple class can increase cognitive overhead without providing meaningful flexibility.

This is sometimes called overengineering. A good developer should know both when to use a pattern and when a straightforward implementation is better.

Warning Sign

If the pattern requires more explanation than the problem it solves, stop and reconsider whether the abstraction is necessary.

Common Mistakes When Learning Java Design Patterns

Memorizing Names Without Understanding Problems

Knowing the names of patterns is less valuable than recognizing the design problem each pattern addresses.

Using Singleton Everywhere

Singleton introduces globally accessible state and can make dependencies less explicit. Use it only when a single shared instance is actually a requirement.

Replacing Every if Statement with a Factory

A factory becomes useful when object creation is a meaningful abstraction. A small conditional that creates one of two simple objects may not require a separate factory class.

Confusing Patterns with Framework Features

A framework may implement or combine several design ideas internally. Learn the underlying object relationships rather than simply memorizing framework annotations or APIs.

Ignoring Simpler Alternatives

Interfaces, composition, lambdas, records, dependency injection, and ordinary classes may solve a problem without requiring a formal pattern implementation.

Best Practices for Using Design Patterns in Java

  • Start with the design problem instead of starting with a pattern name.
  • Prefer small abstractions with clear responsibilities.
  • Favor composition when behavior needs to be changed independently.
  • Keep dependencies explicit where possible.
  • Use interfaces when multiple interchangeable implementations are genuinely useful.
  • Avoid patterns that add abstraction without a practical benefit.
  • Consider testability when introducing shared state or complex object relationships.
  • Document non-obvious design decisions so future developers understand why a pattern was introduced.

A Practical Example: Payment Processing System

Consider an online application that supports card, UPI, and another payment provider. A simple implementation might contain many conditionals throughout the application. A better design can isolate the payment behavior behind an interface and select an implementation during object creation.

Checkout Service
↓
PaymentMethod
CardPayment
UpiPayment
WalletPayment

This design combines ideas from abstraction, dependency inversion, and strategy-style object composition. A factory can then decide which implementation to create. The result is easier to extend because adding another payment method does not require changing every caller.

Design Patterns and Modern Java

Modern Java provides language features that can simplify some traditional pattern implementations. Lambdas can replace small strategy or callback classes. Records can reduce boilerplate for data-oriented immutable models. Enums provide a reliable option for certain singleton-style designs. Interfaces can contain default and static methods, allowing some forms of reusable behavior without deep inheritance hierarchies.

This does not make design patterns obsolete. Instead, modern Java gives developers more tools for expressing the underlying design ideas with less boilerplate.

Key Takeaways

Design patterns are reusable approaches to recurring software design problems, not copy-and-paste code templates.

Creational patterns focus on object creation, while structural patterns focus on object and class composition and behavioral patterns focus on communication and responsibility.

Factory, Builder, and Singleton are common creational patterns.

Adapter, Decorator, and Facade are useful structural patterns.

Strategy, Observer, and Template Method are common behavioral patterns.

Patterns often work best when combined with sound object-oriented principles such as abstraction, composition, and separation of responsibilities.

The most important skill is not memorizing every pattern. It is learning to recognize when a design problem exists and selecting the simplest solution that gives the application the flexibility it actually needs.

Code Examples

java
interface PaymentMethod {
    void pay(double amount);
}

class CardPayment implements PaymentMethod {

    @Override
    public void pay(double amount) {
        System.out.println(
            "Paid ₹" + amount + " using card."
        );
    }
}

class UpiPayment implements PaymentMethod {

    @Override
    public void pay(double amount) {
        System.out.println(
            "Paid ₹" + amount + " using UPI."
        );
    }
}

class PaymentFactory {

    public static PaymentMethod create(
            String type) {

        return switch (type.toLowerCase()) {
            case "card" -> new CardPayment();
            case "upi" -> new UpiPayment();
            default ->
                throw new IllegalArgumentException(
                    "Unsupported payment method"
                );
        };
    }
}

public class FactoryExample {

    public static void main(String[] args) {

        PaymentMethod payment =
            PaymentFactory.create("upi");

        payment.pay(1500);
    }
}
    
java
class User {

    private final String name;
    private final String email;
    private final String phone;
    private final boolean active;

    private User(Builder builder) {
        this.name = builder.name;
        this.email = builder.email;
        this.phone = builder.phone;
        this.active = builder.active;
    }

    public static class Builder {

        private final String name;
        private final String email;

        private String phone;
        private boolean active;

        public Builder(
                String name,
                String email) {

            this.name = name;
            this.email = email;
        }

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

        public Builder active(boolean active) {
            this.active = active;
            return this;
        }

        public User build() {
            return new User(this);
        }
    }

    public String getName() {
        return name;
    }

    public String getEmail() {
        return email;
    }
}

public class BuilderExample {

    public static void main(String[] args) {

        User user =
            new User.Builder(
                "Ananya",
                "ananya@example.com"
            )
            .phone("9876543210")
            .active(true)
            .build();

        System.out.println(
            user.getName()
        );
    }
}
    
java
interface DiscountStrategy {
    double calculateDiscount(
        double price
    );
}

class NoDiscount
        implements DiscountStrategy {

    @Override
    public double calculateDiscount(
            double price) {

        return 0;
    }
}

class FestivalDiscount
        implements DiscountStrategy {

    @Override
    public double calculateDiscount(
            double price) {

        return price * 0.20;
    }
}

class CheckoutService {

    private final DiscountStrategy strategy;

    public CheckoutService(
            DiscountStrategy strategy) {

        this.strategy = strategy;
    }

    public double finalPrice(
            double price) {

        return price
            - strategy.calculateDiscount(price);
    }
}

public class StrategyExample {

    public static void main(String[] args) {

        CheckoutService checkout =
            new CheckoutService(
                new FestivalDiscount()
            );

        double total =
            checkout.finalPrice(5000);

        System.out.println(
            "Final price: ₹" + total
        );
    }
}
    
java
interface MessageSender {
    void send(String message);
}

class BasicSender
        implements MessageSender {

    @Override
    public void send(String message) {

        System.out.println(
            "Sending: " + message
        );
    }
}

class LoggingSender
        implements MessageSender {

    private final MessageSender sender;

    public LoggingSender(
            MessageSender sender) {

        this.sender = sender;
    }

    @Override
    public void send(String message) {

        System.out.println(
            "Log: sending message"
        );

        sender.send(message);
    }
}

public class DecoratorExample {

    public static void main(String[] args) {

        MessageSender sender =
            new LoggingSender(
                new BasicSender()
            );

        sender.send(
            "Welcome to IgKnight"
        );
    }
}
    
java
import java.util.ArrayList;
import java.util.List;

interface Subscriber {
    void onMessage(String message);
}

class NewsPublisher {

    private final List<Subscriber>
        subscribers = new ArrayList<>();

    public void subscribe(
            Subscriber subscriber) {

        subscribers.add(subscriber);
    }

    public void unsubscribe(
            Subscriber subscriber) {

        subscribers.remove(subscriber);
    }

    public void publish(String message) {

        for (Subscriber subscriber :
                subscribers) {

            subscriber.onMessage(message);
        }
    }
}

class EmailSubscriber
        implements Subscriber {

    private final String email;

    public EmailSubscriber(String email) {
        this.email = email;
    }

    @Override
    public void onMessage(String message) {

        System.out.println(
            "Email to "
            + email
            + ": "
            + message
        );
    }
}

public class ObserverExample {

    public static void main(String[] args) {

        NewsPublisher publisher =
            new NewsPublisher();

        publisher.subscribe(
            new EmailSubscriber(
                "user@example.com"
            )
        );

        publisher.publish(
            "New Java lesson available."
        );
    }
}
    

Pro Tip

Learn design patterns by starting with the problem they solve. Do not introduce Factory, Singleton, Strategy, or Decorator simply because the pattern looks cleaner on paper. First identify what needs to change, what is coupled, and what responsibility should be isolated. Then choose the smallest pattern-based design that provides a real benefit.

More Advanced Java lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.