Interview Questions

Top 5 most commonly used design patterns in Java

Author: Interview Questions Posted 5 days ago 26 min read

1. Singleton (Creational)

What it does: Ensures a class has only one instance across the application and provides a global access point to it.
When to use it: Shared resources or stateless services where creating duplicate instances wastes memory or causes inconsistency—such as configuration managers, connection pools, or Spring beans (@Service / @Component are singleton-scoped by default).

class ConfigManager:
    static instance = null
    private constructor()

    static function getInstance():
        if instance is null:
            lock:
                if instance is null:
                    instance = new ConfigManager()
        return instance

2. Factory (Creational)

What it does: Centralizes object creation behind a method or factory class so callers don't need to know which concrete class is being instantiated.
When to use it: When object creation depends on runtime input, configuration, or a type parameter, and you want to keep new calls out of your business logic.

interface Notifier:
    send(message)

class EmailNotifier implements Notifier: ...
class SmsNotifier implements Notifier: ...

class NotifierFactory:
    static function create(channel):
        if channel == "EMAIL": return new EmailNotifier()
        if channel == "SMS":   return new SmsNotifier()
        error("Unsupported channel")

// Usage
notifier = NotifierFactory.create("EMAIL")
notifier.send("Order shipped")

3. Strategy (Behavioral)

What it does: Encapsulates interchangeable algorithms behind a common interface so you can swap behavior at runtime without giant if-else or switch blocks.
When to use it: Pricing rules, sorting/routing logic, payment gateways, or compression/validation rules where behavior varies independently of the caller. (In modern Java, lambdas and functional interfaces like Function or Comparator often replace small strategy classes.)

interface DiscountStrategy:
    apply(amount)

class VipDiscount implements DiscountStrategy:
    apply(amount): return amount * 0.8

class SeasonalDiscount implements DiscountStrategy:
    apply(amount): return amount * 0.9

class CheckoutService:
    constructor(strategy) // Somewhere has kind of this code: strategy = strategyMap.get(type);   strategyMap= {"vipDiscount": ..., "seasonalDiscount": ...};

    function total(amount):
        return strategy.apply(amount)

Why This Is Still Better Than if-else Inside CheckoutService

  1. Single place to change: Adding a "BLACK_FRIDAY" discount means adding a new class and registering it—CheckoutService isn't touched or re-tested for unrelated rules.
  2. Easier unit testing: You can test CheckoutService in isolation with a mock or stub DiscountStrategy, without setting up user tiers or dates.
  3. Avoids repeated if-else: If discount calculation is called in multiple places (cart preview, invoice, refund), choosing the strategy once avoids duplicating the conditional tree everywhere.

4. Builder (Creational)

What it does: Constructs complex objects step by step using readable, chainable methods instead of long constructors with many optional parameters.
When to use it: Request/query objects, configuration structs, or immutable objects that have several optional fields—avoiding telescoping constructors and null arguments.

class HttpRequestBuilder:
    url = ""
    timeoutMs = 3000
    headers = {}

    function url(u):     this.url = u; return this
    function timeout(t): this.timeoutMs = t; return this
    function header(k,v): this.headers[k] = v; return this

    function build():
        require(url is not empty)
        return new HttpRequest(url, timeoutMs, headers)

// Usage
req = new HttpRequestBuilder()
    .url("/api/orders")
    .timeout(5000)
    .header("Authorization", "Bearer ...")
    .build()

5. Decorator (Structural)

What it does: Wraps an object inside another object of the same interface to add behavior dynamically without modifying the original class or subclassing every combination.
When to use it: Stacking cross-cutting behaviors like buffering, logging, metrics, caching, or compression—famously seen in Java's InputStream / OutputStream wrappers (BufferedInputStream, DataInputStream).

interface Reader:
    read()

class FileReader implements Reader:
    read(): return rawBytesFromDisk()

class LoggingReader implements Reader:
    constructor(innerReader)
    read():
        log("Reading data...")
        return innerReader.read()

// Usage: stack behaviors dynamically
reader = new LoggingReader(new FileReader())
reader.read()

Quick Summary

Pattern Core Problem It Solves
Singleton One shared instance across the app
Factory Decouples what gets created from how it's created
Strategy Swaps algorithms/behaviors cleanly at runtime
Builder Makes complex or optional-heavy object creation clean and readable
Decorator Adds composable behavior dynamically without subclass explosion