These are the notes for Low-Level Design (LLD) episode 21: the start of the design patterns part of the course. Instead of starting with a definition, we build a small notification app, watch the obvious code break, fix it with an interface, and then discover that the fix already has a name: the Strategy pattern. From there you'll learn what a design pattern is, how every pattern is written down (name, intent, problem, solution, participants, consequences), where patterns came from (the Gang of Four book), the three families (creational, structural, behavioural), how a pattern differs from an idiom and an architecture style, and the dark side: anti-patterns and pattern overuse. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs and error messages are real.
1. The real-life problem: the tailor's brown-paper pattern
Meena is a tailor in Lucknow. Almost every customer wants a kurta: the same problem, again and again. At first she drew each one from scratch: a whole day's work, and a new small mistake each time. So she traced one good design onto brown paper, a pattern, and now only adjusts it for each customer's size. The paper is not the cloth; it is a guide for cutting the cloth.
Other tailors have their own patterns, and they have names. When one tailor says "use the A-line pattern", everyone in the market knows exactly what he means. Two words carry a whole idea. Cooks have recipes, chess players have named openings ("Sicilian Defence"), and programmers have design patterns.
2. The problem in code: an if-else on the channel
Sharma ji's kirana shop sends customers an "Order ready" message. The obvious code checks the channel name with if-else, once in send() and again in cost() (paise per message). Then WhatsApp is added: the developer adds it to cost() but forgets send().
public class Main {
static String send(String channel, String msg) {
if (channel.equals("SMS")) return "SMS -> 98200 12345: " + msg;
else if (channel.equals("EMAIL")) return "Email -> riya@mail.in: " + msg;
return "Unknown channel: " + channel;
}
static int cost(String channel) { // paise per message
if (channel.equals("SMS")) return 20;
else if (channel.equals("EMAIL")) return 1;
else if (channel.equals("WHATSAPP")) return 15; // new channel added here...
return 0; // ...but forgotten in send()
}
public static void main(String[] args) {
String[] channels = {"SMS", "EMAIL", "WHATSAPP"};
for (String ch : channels)
System.out.println(send(ch, "Order ready") + " | " + cost(ch) + " paise");
}
}
SMS -> 98200 12345: Order ready | 20 paise
Email -> riya@mail.in: Order ready | 1 paise
Unknown channel: WHATSAPP | 15 paise
The customer got nothing, the shop paid 15 paise for it, and the compiler said nothing.
Why it broke
- Everything about one channel is scattered across many
if-elsechains (send,cost, tomorrowlog,retry...). - Adding a channel means editing every chain and remembering all of them.
- Forget one and you get a wrong output with no error.
What we want: everything about one channel in one place, and a compiler that complains when something is missing.
3. The fix: an interface and one class per channel
An interface (episode 3) is a list of methods a class promises to have. Channel says every channel must have send and cost. Each channel becomes one small class holding both. Main loops over Channel objects and never asks which one it has.
import java.util.*;
interface Channel { // one shape every channel must fill
String send(String msg);
int cost();
}
class Sms implements Channel {
public String send(String m) { return "SMS -> 98200 12345: " + m; }
public int cost() { return 20; }
}
class Email implements Channel {
public String send(String m) { return "Email -> riya@mail.in: " + m; }
public int cost() { return 1; }
}
class WhatsApp implements Channel { // a new channel = one new class
public String send(String m) { return "WhatsApp -> Riya: " + m; }
public int cost() { return 15; }
}
public class Main {
public static void main(String[] args) {
for (Channel c : List.of(new Sms(), new Email(), new WhatsApp()))
System.out.println(c.send("Order ready") + " | " + c.cost() + " paise");
}
}
SMS -> 98200 12345: Order ready | 20 paise
Email -> riya@mail.in: Order ready | 1 paise
WhatsApp -> Riya: Order ready | 15 paise
Which send runs is decided at runtime (while the program is running) by the object we pass in: polymorphism (episode 9). A new channel is a new class with no edits to old code: the open-closed principle (episode 13).
The same mistake, now caught by the compiler
import java.util.*;
interface Channel { // one shape every channel must fill
String send(String msg);
int cost();
}
class Sms implements Channel {
public String send(String m) { return "SMS -> 98200 12345: " + m; }
public int cost() { return 20; }
}
class Email implements Channel {
public String send(String m) { return "Email -> riya@mail.in: " + m; }
public int cost() { return 1; }
}
class Push implements Channel { // a new channel... cost() forgotten again
public String send(String m) { return "Push -> Riya's phone: " + m; }
}
public class Main {
public static void main(String[] args) {
for (Channel c : List.of(new Sms(), new Email(), new Push()))
System.out.println(c.send("Order ready") + " | " + c.cost() + " paise");
}
}
Main.java:15: error: Push is not abstract and does not override abstract method cost() in Channel
class Push implements Channel { // a new channel... cost() forgotten again
^
1 error
The interface "remembers" for you: a forgotten method is now a compile error, not a silent wrong output.
4. The twist: it has a name
We didn't invent this shape. Thousands of developers have built it, and it is called the Strategy pattern: define a family of interchangeable ways to do a job behind one interface, and pick one at runtime.
| Real life | In code |
|---|---|
| A chess opening with a name ("Sicilian Defence"): moves people re-use | Strategy: an interface + swappable classes |
| The brown-paper pattern: a guide, not the cloth | A pattern is a template, not code to copy |
| "Use the A-line": tailors talk in names | "Use a Strategy here": developers talk in names |
The name is the real gift: a shared vocabulary. In a code review, "use a Strategy here" replaces a paragraph of explanation.
5. What is a design pattern?
A design pattern is a named, re-usable solution to a recurring design problem in a context.
- Named: Strategy, Observer, Builder. The name lets teams talk about it.
- Re-usable solution: a shape of classes and objects you can apply again and again.
- Recurring problem: one that keeps coming back across many projects (e.g. "many interchangeable ways to do one job").
- Context: the situation in which the solution fits. Outside its context, the same shape can be a bad idea.
- A template, not a library: a library is ready-made code you download and call; a pattern you write yourself, adapted every time.
6. The pattern template
Every pattern in a pattern catalogue is written with the same headings. The Gang of Four format has more sections (Also Known As, Motivation, Applicability, Structure, Collaboration, Implementation, Sample Code, Known Uses, Related Patterns), and there is no single standard format, but these six are the core:
| Heading | Meaning | Strategy (our example) |
|---|---|---|
| Name | A short, memorable label | Strategy |
| Intent | The pattern's goal in one sentence | Let you swap how a job is done, at runtime |
| Problem | The pain that tells you to use it | An if-else on a type, spread across many methods |
| Solution | The shape of classes that fixes it | An interface + one class per way of doing the job |
| Participants | The roles the classes play | Channel = strategy interface; Sms, Email, WhatsApp = concrete strategies; Main = context (the code that uses them) |
| Consequences | The trade-offs: what you gain and what you pay | + a new channel is one new class, compile-checked; − more classes to read and navigate |
A trade-off means you gain something and pay something. Every pattern has a price; the consequences section tells you what it is.
7. Where patterns came from: the Gang of Four
| Year | Event |
|---|---|
| 1977 | The architect Christopher Alexander (with Sara Ishikawa, Murray Silverstein and others) publishes A Pattern Language: 253 patterns for regions, towns, buildings and rooms. Pattern 88 is "Street Cafe". |
| 1987 | Kent Beck and Ward Cunningham apply the pattern idea to programming. |
| 1994 | Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides (released 21 October 1994, 1995 copyright): 23 patterns, each in the same template. |
The four authors (and the book) are nicknamed the Gang of Four, often written GoF. Their book is a pattern catalogue: a collection of patterns, each written the same way, that you can look up like a dish on a menu card. The book also gave two famous principles: "program to an interface, not an implementation" (episode 7) and "favor object composition over class inheritance" (episode 11).
8. Three families of patterns
| Family | Question it answers | Real life (a wedding) | Count |
|---|---|---|---|
| Creational | How are objects made? | The caterer decides what to cook and how much | 5 |
| Structural | How do objects fit together? | A travel plug adapter makes the decorator's foreign plug fit | 7 |
| Behavioural | How do objects share work and talk? | The family splits jobs: who greets, who serves, who pays | 11 |
A tiny taste of each
interface Channel { String send(String m); }
class Sms implements Channel { public String send(String m) { return "SMS: " + m; } }
class Email implements Channel { public String send(String m) { return "Email: " + m; } }
class Channels { // CREATIONAL: one place makes them
static Channel of(String type) {
if (type.equals("SMS")) return new Sms();
if (type.equals("EMAIL")) return new Email();
throw new IllegalArgumentException("no channel: " + type);
}
}
class Urgent implements Channel { // STRUCTURAL: wraps another object
private final Channel inner;
Urgent(Channel inner) { this.inner = inner; }
public String send(String m) { return inner.send("[URGENT] " + m); }
}
public class Main {
public static void main(String[] args) {
Channel sms = Channels.of("SMS");
Channel loud = new Urgent(Channels.of("EMAIL"));
for (Channel c : new Channel[]{sms, loud}) // BEHAVIOURAL: each decides how
System.out.println(c.send("Order ready"));
}
}
SMS: Order ready
Email: [URGENT] Order ready
- Creational:
Channels.ofis the one place that decides which object to create; callers ask by name (a taste of Factory, episode 23). - Structural:
Urgentwraps anotherChanneland adds a tag before passing the call on (a taste of Decorator). - Behavioural: the loop calls
send, and each object decides how (Strategy).
All 23 Gang of Four patterns
| Family | Pattern | Intent in one line |
|---|---|---|
| Creational | Singleton | Ensure a class has only one object, with one global access point |
| Creational | Factory Method | Let a method (often in a subclass) decide which class to create |
| Creational | Abstract Factory | Create families of related objects without naming their concrete classes |
| Creational | Builder | Build a complex object step by step, separating construction from the result |
| Creational | Prototype | Create new objects by copying (cloning) an existing one |
| Structural | Adapter | Make a class with the wrong interface fit the interface a client expects |
| Structural | Bridge | Separate an abstraction from its implementation so both can vary independently |
| Structural | Composite | Treat a tree of objects and a single object the same way |
| Structural | Decorator | Add responsibilities to an object at runtime by wrapping it |
| Structural | Facade | Give one simple interface to a complicated subsystem |
| Structural | Flyweight | Share many small, identical objects to save memory |
| Structural | Proxy | Put a stand-in in front of an object to control access to it |
| Behavioural | Chain of Responsibility | Pass a request along a chain of handlers until one handles it |
| Behavioural | Command | Turn a request into an object, so it can be queued, logged or undone |
| Behavioural | Interpreter | Represent a small language's grammar as classes and evaluate sentences in it |
| Behavioural | Iterator | Walk through a collection without exposing how it is stored |
| Behavioural | Mediator | Let objects talk through one central object instead of to each other |
| Behavioural | Memento | Capture an object's state so it can be restored later (undo) |
| Behavioural | Observer | When one object changes, notify all its subscribers automatically |
| Behavioural | State | Let an object change its behaviour when its internal state changes |
| Behavioural | Strategy | Make a family of algorithms interchangeable behind one interface |
| Behavioural | Template Method | Fix an algorithm's steps in a base class; let subclasses fill in some steps |
| Behavioural | Visitor | Add new operations to a set of classes without changing those classes |
9. Pattern vs idiom vs architecture style
| Idiom | Design pattern | Architecture style | |
|---|---|---|---|
| Size | A few lines | A few classes | The whole system |
| Scope | One language | Any object-oriented language | Any technology |
| Real life | Always turning off the gas after cooking: a habit of this kitchen | The dum biryani method: any cook can adapt it | A 2BHK floor plan: the shape of the whole home |
| Examples | try-with-resources, the for-each loop | Strategy, Observer, Builder | Layered, MVC, microservices |
An idiom is a small, language-specific habit: the usual way to do a common thing in that language. Java's try-with-resources: put anything that implements AutoCloseable in the brackets after try, and Java calls close() when the block ends, even if an exception is thrown.
class Gas implements AutoCloseable {
Gas() { System.out.println("gas ON"); }
public void close() { System.out.println("gas OFF"); }
}
public class Main {
public static void main(String[] args) {
try (Gas g = new Gas()) { // try-with-resources: a Java idiom
System.out.println("cooking dal");
throw new RuntimeException("milk boiled over!");
} catch (RuntimeException e) {
System.out.println("caught: " + e.getMessage());
}
}
}
gas ON
cooking dal
gas OFF
caught: milk boiled over!
The gas went off before the catch block ran. A few lines, one language, no new classes: an idiom.
An architecture style shapes the whole system:
- Layered: the screen (UI) calls the business logic, which calls the database; each layer talks only to the one below.
- MVC (Model-View-Controller): model = the data and rules, view = what the user sees, controller = handles input and connects the two.
- Microservices: one big application split into many small, independently deployed applications that talk over the network.
This course is about the middle size: design patterns.
10. Anti-patterns
Sharma ji runs the shop alone: billing, stock, delivery, accounts. When he falls ill, the shop shuts, because nobody else knows anything. His nephew learns spreadsheets and now uses one for every job, even planning the delivery route.
An anti-pattern is a common solution that looks good but usually makes things worse. The term was coined in 1995 by Andrew Koenig. Anti-patterns get names too, so you can spot and avoid them.
| Anti-pattern | Meaning | Real life | Fix |
|---|---|---|---|
| God class (god object) | One class that knows and does everything; every change touches it, every bug hides in it | Sharma ji doing every job | Split by responsibility (SRP, episode 12) |
| Golden hammer | Using one familiar tool or pattern for every problem: "if all you have is a hammer, everything looks like a nail" | The nephew's spreadsheet for everything | Choose the tool for the problem |
11. Pattern overuse
Pattern overuse is the golden hammer applied to patterns: adding patterns where no problem needs them. Someone just learned factories and wants to print a greeting:
interface Greeter { String greet(String name); }
interface GreeterFactory { Greeter create(); }
class NamasteGreeter implements Greeter {
public String greet(String n) { return "Namaste, " + n; }
}
class NamasteGreeterFactory implements GreeterFactory {
public Greeter create() { return new NamasteGreeter(); }
}
class GreeterProvider {
static GreeterFactory factory() { return new NamasteGreeterFactory(); }
}
public class Main {
public static void main(String[] args) {
Greeter g = GreeterProvider.factory().create(); // 5 types, 3 calls...
System.out.println(g.greet("Riya"));
System.out.println("Namaste, " + "Riya"); // ...for this one line
}
}
Namaste, Riya
Namaste, Riya
Same output. Two interfaces and three classes, five extra types, solve no problem. It compiles and runs, and is still wrong: more code to read and change (KISS and YAGNI, episode 17). No problem, no pattern.
12. How to learn design patterns
- Start from the problem. Never memorise a diagram first. Ask: what pain does this pattern remove?
- Recognise code smells. A code smell is a sign in code that something may be wrong (like a smell from the kitchen): an
if-elseon a type, copy-pasted blocks, a giant class, a constructor with ten parameters. Each smell points to a pattern. - Code each pattern yourself: a small, real example that you compile and run.
- Know the consequences, especially when not to use it. Interviewers ask this.
Common mistakes
| Mistake | Exact message / symptom | Why | Fix |
|---|---|---|---|
if-else on a type in many methods |
Unknown channel: WHATSAPP \| 15 paise |
One channel's facts scattered; one chain forgotten | Interface + one class per channel |
class Push implements Channel without cost() |
Push is not abstract and does not override abstract method cost() in Channel |
A promised interface method is missing | Implement every interface method (or make the class abstract) |
Factory + interfaces for one println |
no error: Namaste, Riya with 5 extra types |
A pattern with no problem (overuse) | Write the simple line |
Channels.of("FAX") with no matching branch |
IllegalArgumentException: no channel: FAX |
The creation method doesn't know that type | Add the type, or validate input earlier |
| Memorising UML diagrams of patterns | no error: can't say when to use one | Pattern learned without its problem | Learn problem, intent and consequences |
| Calling a pattern by the wrong name | no error: confused teammates | The vocabulary is the point | Use the catalogue names exactly |
Mini project
Sharma ji now wants discounts: regular customers pay full price, a festival offer gives 10% off, and a "buy above Rs 500" offer gives Rs 50 off. Build it with the Strategy shape (an interface Discount with int apply(int amount)), then write its pattern template.
Solution
interface Discount { int apply(int amount); String name(); }
class NoDiscount implements Discount {
public int apply(int a) { return a; }
public String name() { return "regular"; }
}
class Festival implements Discount {
public int apply(int a) { return a - a / 10; }
public String name() { return "festival 10%"; }
}
class Above500 implements Discount {
public int apply(int a) { return a > 500 ? a - 50 : a; }
public String name() { return "Rs 50 off above 500"; }
}
public class Main {
public static void main(String[] args) {
Discount[] offers = {new NoDiscount(), new Festival(), new Above500()};
for (Discount d : offers)
System.out.println(d.name() + ": Rs " + d.apply(600));
}
}
Output:
regular: Rs 600
festival 10%: Rs 540
Rs 50 off above 500: Rs 550
Template: Name Strategy. Intent swap the discount rule at runtime. Problem an if-else on offer type in billing, reports and receipts. Solution a Discount interface + one class per offer. Participants Discount (strategy), NoDiscount/Festival/Above500 (concrete strategies), Main (context). Consequences + a new offer is one class; − more small classes.
Practice
1. In your own words, what are the four parts of the definition "a named, re-usable solution to a recurring design problem in a context"?
Answer
Named: it has a label teams share. Re-usable solution: a shape you apply again. Recurring problem: it keeps coming up in many projects. Context: the situation where it fits; outside it, the pattern may hurt.
2. Creational, structural or behavioural? (a) Builder (b) Adapter (c) Observer (d) Proxy (e) Prototype (f) Command
Answer
(a) Creational (b) Structural (c) Behavioural (d) Structural (e) Creational (f) Behavioural.
3. Idiom, design pattern or architecture style? (a) the for-each loop (b) microservices (c) Strategy (d) try-with-resources (e) MVC
Answer
(a) Idiom (b) Architecture style (c) Design pattern (d) Idiom (e) Architecture style.
4. Add a Telegram channel to the Strategy program in section 3. Which existing classes did you change?
Answer
class Telegram implements Channel {
public String send(String m) { return "Telegram -> @riya: " + m; }
public int cost() { return 0; }
}
Add new Telegram() to the list in main. No existing channel class changes: that's the open-closed principle at work. Output adds Telegram -> @riya: Order ready | 0 paise.
5. Why is the GreeterFactory program in section 11 bad even though it works?
Answer
It adds five types and three calls to solve no problem: there is only one greeting and nothing varies. More code to read, test and change, with no benefit. That's pattern overuse.
Quick quiz
class Urgent implements Channel {
private final Channel inner;
Urgent(Channel inner) { this.inner = inner; }
public String send(String m) {
return inner.send("[URGENT] " + m);
}
}
Which family does this shape belong to?
- A. Creational
- B. Structural
- C. Behavioural
- D. An idiom
Answer
B. Urgent wraps another Channel object and adds to it: it's about how objects fit together, so structural (this shape is the Decorator pattern).
Interview questions
- What is a design pattern? A named, re-usable solution to a recurring design problem in a context. It is a template you adapt, not code you copy.
- Who are the Gang of Four? Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, authors of Design Patterns: Elements of Reusable Object-Oriented Software (1994), which catalogued 23 patterns.
- What are the three categories? Creational (object creation, 5), structural (composing classes and objects, 7), behavioural (responsibilities and communication, 11).
- What sections describe a pattern? Name, intent, problem (motivation/applicability), solution (structure), participants, collaborations, consequences, implementation, sample code, known uses, related patterns.
- Pattern vs library vs framework? A library is code you call; a framework is code that calls you; a pattern is an idea you implement yourself.
- Pattern vs idiom vs architecture style? Idiom: a few lines, one language. Pattern: a few classes, any OO language. Architecture style: the shape of the whole system.
- What is an anti-pattern? Give two. A common solution that backfires (term coined by Andrew Koenig, 1995). God class, golden hammer.
- When should you not use a pattern? When the problem it solves isn't present, or when the simple code is clear enough; the pattern's consequences (more classes, indirection) would cost more than they save.
- Where did the idea of patterns come from? Christopher Alexander's A Pattern Language (1977), for buildings; applied to software by Kent Beck and Ward Cunningham in 1987.
- Name two GoF principles. "Program to an interface, not an implementation" and "favor object composition over class inheritance".
Glossary
| Term | Meaning, with an example |
|---|---|
| Design pattern | A named, re-usable solution to a recurring design problem in a context. Strategy |
| Gang of Four (GoF) | Nickname for Gamma, Helm, Johnson and Vlissides, authors of the 1994 Design Patterns book |
| Pattern catalogue | A collection of patterns, each written in the same template, to look up by name. The GoF book |
| Creational patterns | Patterns about how objects are made. Singleton, Builder, Channels.of |
| Structural patterns | Patterns about how classes and objects fit together. Adapter, Decorator (Urgent) |
| Behavioural patterns | Patterns about how objects share work and communicate. Strategy, Observer |
| Intent | A pattern's goal in one sentence. Strategy: swap how a job is done at runtime |
| Problem | The situation and pain that tells you to use a pattern. An if-else on a type everywhere |
| Solution | The shape of classes and objects that fixes the problem. An interface + one class per way |
| Participants | The roles the classes play in a pattern. Channel, Sms, Main |
| Consequences | The trade-offs of using a pattern. + new class per channel; − more classes |
| Trade-off | Gaining one thing by paying another |
| Context | The situation in which a pattern fits; outside it, the pattern may hurt |
| Recurring problem | A design problem that keeps coming back across projects |
| Template (pattern sense) | A guide you adapt, like a tailor's paper pattern; not code to copy |
| Library | Ready-made code you download and call |
| Idiom | A small, language-specific habit. Java's try-with-resources |
| Architecture style | The shape of a whole system. Layered, MVC, microservices |
| Pattern vs idiom vs architecture style | Few classes, any OO language vs few lines, one language vs whole system |
| Layered architecture | UI calls business logic, which calls the database |
| MVC | Model (data), view (screen), controller (input) |
| Microservices | One app split into many small apps talking over a network |
| try-with-resources | try (R r = ...) { }: Java calls r.close() automatically when the block ends |
AutoCloseable |
Interface with close(); required for try-with-resources |
| Anti-pattern | A common solution that looks good but usually backfires. God class |
| God class | One class that knows and does everything |
| Golden hammer | Using one familiar tool or pattern for every problem |
| Pattern overuse | Applying patterns where no problem needs them. A factory for one println |
| Code smell | A sign in code that something may be wrong. if-else on a type |
| Strategy | Behavioural pattern: interchangeable algorithms behind one interface, chosen at runtime |
| Concrete strategy | One implementation of the strategy interface. Sms |
| Wrapper | An object that holds another and adds behaviour around its calls. Urgent |
| Runtime | While the program is running (vs compile time) |
| Interface | A list of methods a class promises to implement (episode 3) |
| Open-closed principle | Open for extension, closed for modification (episode 13) |
Summary
- A design pattern is a named, re-usable solution to a recurring design problem in a context: a template, not a library.
- Patterns are described by name, intent, problem, solution, participants, consequences.
- Origin: Alexander's A Pattern Language (1977) → Beck and Cunningham (1987) → the Gang of Four book (1994), a catalogue of 23 patterns.
- Creational (making, 5), structural (fitting, 7), behavioural (sharing work, 11).
- Idiom < pattern < architecture style, by size.
- Anti-patterns (god class, golden hammer) backfire; pattern overuse adds code without solving a problem.
- Learn patterns problem first, spot code smells, code each one, and know when not to use it.
Next episode: The Singleton pattern.