Design Patterns in Java: What They Are, When to Use Them, and When Not To

Maya runs a small online bookstore. Her checkout code started simple: add up the cart, apply a discount, print a receipt. Then the business grew. Students asked for 10% off. A seasonal sale added 15%. Loyal customers earned 5%. Each new rule meant opening the checkout code, adding another branch, and re-testing everything the checkout already did — because every edit touched the same method that all the old rules lived in.

This is the exact moment design patterns exist for. Not as clever tricks, and not as a badge of seniority — as answers to a recurring question: this part of my program keeps changing; how do I shape the code so the next change is small and safe? This post answers that question with one pattern, worked end to end, and gives you the map for the rest of the track. The principle for this lesson: give what varies a name and a seam.

1. The customer problem

Maya's checkout has one job that never changes — turn a cart into a total and a receipt — and one part that changes constantly: the discount rule. Today there are three rules, and a fourth (buy-two-get-one-free) is already being discussed. The requirement from Maya is plain: adding a discount rule must not risk breaking the rules that already work.

Notice what she did not ask for. She did not ask for a framework, a plugin system, or a rules engine. She asked for one property: new rules arrive without touching old rules. Hold that thought — it is the test every design decision in this post will be measured against.

2. Clarify the ask: what varies, what stays

Before writing any code, split the problem in two:

  • What stays stable: the checkout flow. Take a subtotal, subtract a discount, return a total. That shape will not change when the fourth or fifth rule arrives.
  • What varies: the discount rule itself — the percentage, the conditions, and eventually the inputs it needs.

This split is the whole game. Most bad designs come from gluing a varying part to a stable part so tightly that changing one forces you to re-verify the other. A design pattern, at its core, is a proven way to cut along that seam. As a rule of thumb — not a law — if you cannot point at the seam, you do not have a design yet; you have a pile of code that happens to work today.

3. The minimum concept: a pattern is a name for a proven shape

A design pattern is not a library, not a class you import, and not code to copy-paste. It is a named, proven solution to a recurring design problem, described well enough that two developers can say its name and picture the same shape. The names come from the 1994 book Design Patterns by Gamma, Helm, Johnson, and Vlissides — the "Gang of Four" — and they are still the shared vocabulary of working Java developers, because the problems they describe keep recurring.

Patterns are traditionally grouped into three categories. This track covers the ones working Java developers reach for most often:

The three pattern categories — and what each one answers CREATIONAL How objects are made Singleton Factory Method Abstract Factory Builder Posts 2–4 STRUCTURAL How objects fit together Adapter Facade Decorator Proxy Posts 5–6 BEHAVIORAL How objects talk & act Observer Strategy · State Command Template Method Posts 7–9 Post 10 maps these patterns onto Spring, the JDK, and your own code.

One warning before we build: a pattern is a tool, not a goal. Applying a pattern where nothing varies adds indirection without buying anything — more types to read, more files to open, no change made safer. The question is never "which pattern can I fit here?" but "what varies, and does this pattern make that variation cheaper?" Keep that question in your pocket for the rest of the track.

4. Build: the naive checkout, then the seam

Here is Maya's checkout as most of us would first write it. Amounts are in cents, stored as long, so there is no floating-point rounding to argue about:

enum DiscountType { NONE, STUDENT, SEASONAL, LOYALTY }

final class NaiveCheckout {
    long totalCents(long subtotalCents, DiscountType type) {
        long discount = 0;
        if (type == DiscountType.STUDENT) {
            discount = subtotalCents / 10;        // 10%
        } else if (type == DiscountType.SEASONAL) {
            discount = subtotalCents * 15 / 100;  // 15%
        } else if (type == DiscountType.LOYALTY) {
            discount = subtotalCents / 20;        // 5%
        }
        return subtotalCents - discount;
    }
}

This works. It is also a trap, and the trap is easy to name: every new rule edits this method. The fourth rule means a fourth branch, a fourth chance to mistype a percentage, and a full re-test of the checkout — because the old rules and the new rule share one body. Maya's requirement — new rules must not risk old rules — fails by construction.

Now cut along the seam. The varying part gets a name — a DiscountStrategy — and the stable part, the checkout, talks only to that name:

// The seam: one method, one job — how much to subtract, in cents.
interface DiscountStrategy {
    long discountCents(long subtotalCents);
}

final class StudentDiscount implements DiscountStrategy {
    @Override public long discountCents(long subtotalCents) {
        return subtotalCents / 10;  // 10%; integer division truncates — see section 6
    }
}

final class SeasonalDiscount implements DiscountStrategy {
    @Override public long discountCents(long subtotalCents) {
        return subtotalCents * 15 / 100;  // 15%
    }
}

final class LoyaltyDiscount implements DiscountStrategy {
    @Override public long discountCents(long subtotalCents) {
        return subtotalCents / 20;  // 5%
    }
}

final class NoDiscount implements DiscountStrategy {
    @Override public long discountCents(long subtotalCents) {
        return 0;
    }
}

The checkout now depends on the interface, never on a specific rule:

final class Checkout {
    private final DiscountStrategy discount;

    Checkout(DiscountStrategy discount) {
        if (discount == null) {
            throw new IllegalArgumentException("discount must not be null");
        }
        this.discount = discount;
    }

    long totalCents(long subtotalCents) {
        if (subtotalCents < 0) {
            throw new IllegalArgumentException("subtotal must not be negative");
        }
        long discountAmount = discount.discountCents(subtotalCents);
        if (discountAmount < 0 || discountAmount > subtotalCents) {
            throw new IllegalStateException("discount out of range: " + discountAmount);
        }
        return subtotalCents - discountAmount;
    }
}

This shape — an interface for the varying behavior, with interchangeable implementations picked at runtime — is the Strategy pattern. Run it:

public class PatternDemo {
    public static void main(String[] args) {
        long subtotal = 5000; // $50.00, in cents
        System.out.println("Student : " + new Checkout(new StudentDiscount()).totalCents(subtotal));
        System.out.println("Seasonal: " + new Checkout(new SeasonalDiscount()).totalCents(subtotal));
        System.out.println("Loyalty : " + new Checkout(new LoyaltyDiscount()).totalCents(subtotal));
        System.out.println("No disc.: " + new Checkout(new NoDiscount()).totalCents(subtotal));
    }
}
Student : 4500
Seasonal: 4250
Loyalty : 4750
No disc.: 5000

Check the arithmetic by hand: 10% of 5000 is 500 (total 4500), 15% is 750 (total 4250), 5% is 250 (total 4750). Now measure the design against Maya's requirement. Adding a fifth rule means writing one new class that implements DiscountStrategy — the checkout file is never opened, and the old rules' tests still pass untouched, because their code did not change. That is what the seam buys.

5. Break it: the rule that doesn't fit the seam

Patterns solve the problem they were designed for — not every problem. Here comes the fourth rule Maya was warned about: buy-two-get-one-free. It cannot be expressed with the seam we just built, because it does not depend on the subtotal at all. It depends on which items are in the cart and how many of each. Our interface only receives a total:

// A record is a compact class for plain data (Java 16+).
record CartItem(String title, long priceCents, int quantity) {}

// Buy-two-get-one-free needs the line items, not a subtotal —
// so it cannot honestly implement DiscountStrategy.
interface CartDiscount {
    long discountCents(java.util.List<CartItem> items);
}

This is the break, and it is instructive rather than embarrassing. Two lessons fall out of it. First, a seam is shaped by the inputs it passes through: choose the wrong inputs and the next real requirement will not fit. Second, the fix is not to abandon the pattern — it is to widen the seam deliberately, for example by passing the cart itself to the strategy instead of just the subtotal, and accepting that every existing strategy then needs a small, honest update. A pattern that cannot admit its own limits is a dogma, not a design.

There is a second, quieter break worth naming: the naive version's test burden. With the if-else checkout, one test method per rule still shares the method under test, so a change to any branch can break every rule's test. With strategies, each rule is its own class with its own tests, and the checkout's tests only cover the stable flow. The design didn't just make changes safer — it made the tests tell you which rule broke.

6. Harden it: make the seam production-shaped

Three small hardenings turn the classroom version into something you could ship. First, strategies here are stateless — they hold no fields and keep no memory between calls — which makes them safe to share and trivial to test. As a rule of thumb, prefer stateless strategies; a strategy that secretly accumulates state is a bug waiting for a second customer.

Second, give callers one place to look strategies up by name, instead of scattering new calls through the codebase:

import java.util.Map;

final class Discounts {
    static final Map<String, DiscountStrategy> ALL = Map.of(
        "none", new NoDiscount(),
        "student", new StudentDiscount(),
        "seasonal", new SeasonalDiscount(),
        "loyalty", new LoyaltyDiscount()
    );

    static DiscountStrategy named(String name) {
        DiscountStrategy found = ALL.get(name);
        if (found == null) {
            throw new IllegalArgumentException("unknown discount: " + name);
        }
        return found;
    }
}

Third, verify with explicit checks, not assertions. Assertions can be switched off at runtime, so they are documentation, not a safety net — the checks below throw whether assertions are enabled or not:

public class CheckoutCheck {
    static void check(String label, long actual, long expected) {
        if (actual != expected) {
            throw new IllegalStateException(label + ": expected " + expected + " but got " + actual);
        }
        System.out.println(label + ": OK (" + actual + ")");
    }

    public static void main(String[] args) {
        check("student", new Checkout(new StudentDiscount()).totalCents(5000), 4500);
        check("seasonal", new Checkout(new SeasonalDiscount()).totalCents(5000), 4250);
        check("loyalty", new Checkout(new LoyaltyDiscount()).totalCents(5000), 4750);
        check("none", new Checkout(new NoDiscount()).totalCents(5000), 5000);
        check("negative subtotal rejected", rejectsNegative(), 1);
    }

    // Returns 1 only if the negative subtotal is rejected as required.
    static long rejectsNegative() {
        try {
            new Checkout(new NoDiscount()).totalCents(-100);
        } catch (IllegalArgumentException expected) {
            return 1;
        }
        return 0;
    }
}
student: OK (4500)
seasonal: OK (4250)
loyalty: OK (4750)
none: OK (5000)
negative subtotal rejected: OK (1)

One honest detail in the code above: StudentDiscount uses integer division, so a $50.05 subtotal (5005 cents) gives a discount of 500 cents, not 500.5 — the half-cent is truncated, not rounded. Truncation versus rounding is a business decision, not a programming detail: Maya's accountant, not the developer, should choose it, and the choice should be written down next to the code. If you remember one sentence from this section, make it that one.

7. Communicate: explain it to a human

The code is only half the job. Here is how you explain this change to Maya, without jargon:

"Before, every discount lived inside the checkout, so adding one meant re-testing all of them. Now each discount is its own sealed unit, and the checkout just asks whichever unit you pick for its number. Adding the next discount means adding one new unit — the old ones are never touched. The one thing this shape can't do yet is deals that depend on individual items, like buy-two-get-one-free; when that arrives, we'll widen the seam on purpose rather than hack around it."

If she understands that paragraph, she understands the design — and she can approve the next change with confidence, because she knows exactly what it will and won't touch.

Field check

Five rules to carry into the rest of the track:

  1. A pattern is a name for a proven shape, not code to copy. If you can't say what varies, you don't have a design problem yet — you have code that works today.
  2. Give what varies a name and a seam. An interface for the varying part, chosen at runtime, is the simplest seam there is — and it is the Strategy pattern.
  3. Measure a design against the next change, not the current code. The naive checkout was shorter. The strategy version is safer to change. Shorter is not the metric.
  4. Every seam has a shape, and the shape limits what fits. A subtotal-only strategy cannot express an item-level deal. Admit that early, widen deliberately.
  5. Business decisions belong to the business. Truncation vs. rounding, discount caps, unknown-name handling — the code enforces them, but a human chooses them, and the choice should be written down.

Continue: Java Learning Roadmap 2026

Comments

Popular posts from this blog

JSP Servlet Interview Questions For Freshers Series 1

What are the core classes and interfaces of hibernate 4

Java Banking Finance Services and Insurance (BFSI) domain interview questions