Skip to lesson

What a design pattern is and is not

ShopLite's code has grown messy: a giant switch for delivery fees, another for payments, and every new rule edits working code. Developers hit this problem so often that its fix got a name. This lesson shows what such a name means.

A pattern is a named, reusable solution

A design pattern is a named, reusable solution to a design problem that keeps coming back. It describes how classes and objects work together, so you reuse the idea in many programs, not copied code.

ShopLite's delivery fee starts as a switch on a rule name. Below, the same fees are written twice: first with the switch, then with one small class per rule.

Before: one fee method holds a switch with a case for STANDARD, EXPRESS and FREE_ABOVE_499, so every new rule edits that method. After, the Strategy pattern: Checkout holds a DeliveryFeeRule interface and one class per rule implements it, so a new rule is a new class.

Example 1 · Strategy: a name for a solution you may already use

NamedSolutionDemo.javaJava
import java.util.List;
// Without a pattern: every new rule edits this methodclass FeeCalculatorWithSwitch {    double fee(String rule, double orderTotal) {        switch (rule) {            case "STANDARD": return 40;            case "EXPRESS": return 99;            case "FREE_ABOVE_499": return orderTotal >= 499 ? 0 : 40;            default: throw new IllegalArgumentException("Unknown rule " + rule);        }    }}
// The Strategy pattern: one interface, one class per ruleinterface DeliveryFeeRule {    double fee(double orderTotal);}
class StandardDelivery implements DeliveryFeeRule {    public double fee(double orderTotal) { return 40; }}
class ExpressDelivery implements DeliveryFeeRule {    public double fee(double orderTotal) { return 99; }}
class FreeAbove499 implements DeliveryFeeRule {    public double fee(double orderTotal) { return orderTotal >= 499 ? 0 : 40; }}
public class NamedSolutionDemo {    public static void main(String[] args) {        FeeCalculatorWithSwitch old = new FeeCalculatorWithSwitch();        System.out.printf("Switch: EXPRESS on Rs 650 -> Rs %.0f%n", old.fee("EXPRESS", 650));
        List<DeliveryFeeRule> rules = List.of(new StandardDelivery(), new ExpressDelivery(), new FreeAbove499());        for (DeliveryFeeRule rule : rules) {            System.out.printf("%s on Rs 650 -> Rs %.0f%n", rule.getClass().getSimpleName(), rule.fee(650));        }    }}
Output
Switch: EXPRESS on Rs 650 -> Rs 99
StandardDelivery on Rs 650 -> Rs 40
ExpressDelivery on Rs 650 -> Rs 99
FreeAbove499 on Rs 650 -> Rs 0

What this code does

  • Both versions compute the same fees. The switch must be edited for every new rule; with Strategy a new rule is a new class.
  • Saying "delivery fees use Strategy" tells another developer the whole structure: one interface, one class per rule, chosen at run time.

The second version is the Strategy pattern: each rule gets its own class behind one interface. It is the Open/Closed idea from the SOLID lesson, now with a name, so a team can say "use a Strategy here" instead of describing the whole structure.

Common mistake: thinking a pattern is a class you import. There is no Strategy class to download; the pattern is the shape you build.

Predict the output

Predict the fee

Each lambda is one delivery-fee rule. What does it print?

Round 1 of 2

interface Fee { double of(double total); }
Fee standard = total -> 40;
Fee freeAbove = total -> total >= 499 ? 0 : 40;
System.out.println(standard.of(650) + " " + freeAbove.of(650));

The parts of a pattern

The intent of a pattern is one sentence that says what the pattern does, such as "keep a family of interchangeable rules and pick one at run time". It is the first thing you read about any pattern.

Every pattern description has the same four parts: intent, problem, structure and consequences. Below, Strategy is written up that way.

Text
Pattern:      Strategy (behavioural)Intent:       Keep a family of interchangeable rules, and pick one at run time.Problem:      A method grows one branch per rule (delivery fee, discount, payment).Structure:    Context --holds--> Strategy interface <-- one class per ruleConsequences: + a new rule is a new class; each rule can be tested alone              - more classes; someone must choose which strategy to use

Learn a pattern by these four parts, not by its class diagram alone:

  • Intent: one sentence on what the pattern does.
  • Problem: the situation that tells you it fits.
  • Structure: the roles (classes and interfaces) and how they connect.
  • Consequences: what you gain and what it costs.

The consequences matter most in interviews. Every pattern adds classes or indirection, so you use it only when the gain is bigger than that cost.

Creational, structural and behavioural families

The Gang of Four (GoF) are Gamma, Helm, Johnson and Vlissides, the authors of the 1994 book Design Patterns that catalogued 23 patterns in three families: creational, structural and behavioural.

The 23 classic patterns fall into three families, by what each one is mainly about. Below is one tiny pattern from each family in a ShopLite setting.

Example 2 · One small pattern from each family

PatternFamiliesDemo.javaJava
// Creational: hides which class is createdinterface PaymentMethod {    String pay(double amount);}
class CardPayment implements PaymentMethod {    public String pay(double amount) { return String.format("card Rs %.2f", amount); }}
class UpiPayment implements PaymentMethod {    public String pay(double amount) { return String.format("UPI Rs %.2f", amount); }}
class PaymentFactory {    static PaymentMethod create(String type) {        return switch (type) {            case "CARD" -> new CardPayment();            case "UPI" -> new UpiPayment();            default -> throw new IllegalArgumentException("Unknown payment type: " + type);        };    }}
// Structural: makes an old class fit the interface we useclass OldSmsApi {    int sendText(String mobile, String body) {        System.out.println("[old API] " + mobile + " <- " + body);        return 200;    }}
interface NotificationChannel {    void send(String to, String text);}
class SmsAdapter implements NotificationChannel {    private final OldSmsApi api = new OldSmsApi();
    public void send(String to, String text) {        api.sendText("+91" + to, text);    }}
// Behavioural: how objects share the work, chosen at run timeinterface DiscountRule {    double apply(double amount);}
public class PatternFamiliesDemo {    public static void main(String[] args) {        PaymentMethod method = PaymentFactory.create("UPI");        System.out.println("Creational  -> " + method.pay(499));
        NotificationChannel sms = new SmsAdapter();        System.out.print("Structural  -> ");        sms.send("9876543210", "ORD-71 confirmed");
        DiscountRule festival = amount -> amount * 0.9;        DiscountRule none = amount -> amount;        System.out.printf("Behavioural -> festival Rs %.2f, normal Rs %.2f%n", festival.apply(1000), none.apply(1000));    }}
Output
Creational  -> UPI Rs 499.00
Structural  -> [old API] +919876543210 <- ORD-71 confirmed
Behavioural -> festival Rs 900.00, normal Rs 1000.00

What this code does

  • Creational: PaymentFactory.create decides which class to build, so the caller never writes new UpiPayment().
  • Structural: SmsAdapter makes the old sendText API fit the NotificationChannel interface without changing either side.
  • Behavioural: each DiscountRule is a different way to do the same job, picked at run time (here as lambdas).

The families, by what each is mainly about:

  • Creational patterns control how objects are created: Singleton, Factory Method, Abstract Factory, Builder, Prototype.
  • Structural patterns control how objects are combined: Adapter, Decorator, Proxy, Facade, Composite, Bridge, Flyweight.
  • Behavioural patterns control how objects share work and talk: Strategy, Observer, Template Method, Command, Chain of Responsibility, State, Iterator and more.

To classify a pattern, ask whether it is mainly about making objects, connecting objects, or dividing behaviour between objects.

What patterns are not

Pattern-itis is using design patterns where no matching problem exists. It adds classes, files and indirection and gains nothing in return.

A pattern is not a library, not a copy-paste template and never the goal. Below, a greeting that never changes is built with a pattern, then written plainly.

Example 3 · A pattern used for its own sake

PatternForItsOwnSakeDemo.javaJava
// Pattern for its own sake: three types to build one greeting that never changesinterface GreetingStrategy {    String greet(String name);}
class DefaultGreeting implements GreetingStrategy {    public String greet(String name) {        return "Welcome to ShopLite, " + name;    }}
class GreetingStrategyFactory {    static GreetingStrategy create() {        return new DefaultGreeting();    }}
// What the problem really neededclass Greetings {    static String welcome(String name) {        return "Welcome to ShopLite, " + name;    }}
public class PatternForItsOwnSakeDemo {    public static void main(String[] args) {        String fancy = GreetingStrategyFactory.create().greet("Asha");        String plain = Greetings.welcome("Asha");        System.out.println(fancy);        System.out.println(plain);        System.out.println("Same text: " + fancy.equals(plain));    }}
Output
Welcome to ShopLite, Asha
Welcome to ShopLite, Asha
Same text: true

What this code does

  • The Strategy-plus-Factory version has three types for a greeting with one form that never changes. There is no problem for the patterns to solve.
  • The plain static method gives the same result with one small class. The design is better because it has less in it.

Role names such as ConcreteStrategy are placeholders; the real shape adapts to your own names. Start from a real problem, such as a growing switch or a class you cannot change, and only then reach for the pattern that solves it.

Common mistake: adding a pattern to look professional. If a review finds three types doing the job of one method, delete the pattern and keep the plain code.

Order of execution

Using a pattern well

Put the steps in the order a careful developer follows.

Map of this section

Every pattern in this section solves one concrete ShopLite problem, so you always see the problem first:

  • Creational: one shared AppConfig (Singleton), creating Card, UPI and Wallet payments (Factory), matching tax and shipping per region (Abstract Factory), building a Receipt with many fields (Builder), copying cart templates (Prototype).
  • Structural: fitting a third-party payment SDK (Adapter), adding logging and retries to a gateway (Decorator), loading images lazily (Proxy), one placeOrder call over many services (Facade), categories inside categories (Composite).
  • Behavioural: discount and shipping rules (Strategy), order events for email and inventory (Observer), cart undo (Command), order validation steps (Chain of Responsibility), order status from Placed to Delivered (State).

Later modules show the same patterns inside the JDK and Spring, when to refactor towards them, and how to use them in low-level design interview problems.

Next step

Check your understanding

10 quick questions