Resources · Low-level design (LLD)

Design Patterns for Low-Level Design

Every design pattern you need for a low-level design (LLD) interview, explained in plain English. Each of the 26 patterns has an everyday analogy, a class diagram, the problem it solves, when to use it and when not to, and a runnable example in Python, Java, C++, JavaScript and Go. Written so a college student can follow it and an SDE-3 still finds the trade-offs worth reading.

What low-level design is

Low-level design (LLD) is the part of design that happens inside one program or service. You decide which classes exist, what methods and data each one has, which interfaces they share and how they relate to each other. In an interview you get a small system such as a Parking Lot, an Elevator or a Vending Machine, and you design the classes and write the key code.

Design patterns are named, proven solutions to design problems that keep coming back. They are not libraries or copy-paste code. They are shapes, such as 'put each algorithm in its own class behind one interface' (Strategy). Knowing the shape lets you solve a new problem quickly and lets you explain your design to someone else in one word.

High-level design (HLD)Low-level design (LLD)
Question it answersWhich services and storage, and how does it scale?Which classes and interfaces, and how do they work together?
PiecesLoad balancers, caches, queues, databasesClasses, interfaces, methods, relationships
Typical problemDesign Twitter, URL shortenerDesign Parking Lot, Elevator, Chess
Where patterns liveArchitecture-level equivalents (queues, sagas)The 23 classic patterns on this page
Practice it in PRISMSystem design guides and simulatorThis guide

How an LLD interview usually goes

  1. Clarify the requirements. What must it do? What is out of scope? Write them down.
  2. Find the nouns and verbs. Nouns become classes (Vehicle, Ticket, Spot). Verbs become methods (park, pay, exit).
  3. Draw the relationships. Who contains whom, who inherits from whom, who only uses whom.
  4. Spot the changing parts and use a pattern. Pricing rules will change: Strategy. Spot states: State. Do not add a pattern without a reason.
  5. Write the core code and walk through one example. Keep it small, runnable in your head, and handle one edge case.

How to use this guide at your level

Everyone reads the same page, but you should read it differently.

  • College students and beginners

    New to design patterns

    Read the analogy and 'The idea' first, then run the code and change one thing. Start with Strategy, Observer, Factory Method, Singleton and Decorator: they cover most of what you will meet. Skip 'Going deeper' until it makes sense; it will be there when you are ready.

  • 0 to 2 years

    SDE-1

    Your goal is to recognise a pattern from a problem statement and write the interface first. Use the Pattern Finder, learn the five or six most common patterns cold, and practice saying one sentence about why each fits. Always write the code, not only the diagram.

  • 2 to 5 years

    SDE-2

    Interviewers now ask 'why this and not that?'. Read 'Going deeper' and the look-alike table. Focus on trade-offs, testability (Dependency Injection), thread safety (Singleton, Object Pool, Observer) and on knowing when a plain function or an if is the better answer.

  • 5 or more years

    SDE-3 and above

    Expect to connect patterns to architecture: middleware is Chain of Responsibility, ports and adapters is Adapter, event sourcing is Command, a message broker is Mediator. Be ready to challenge the premise, to talk about extension points, API stability and concurrency, and to say 'no pattern needed here' and defend it.

Every pattern below has the same layout, so you always know where to look: In one line, Explain it like I am new, The problem, The idea, the diagram, the code, Use it when, Skip it when, Where it shows up in LLD, Going deeper (the senior-level notes) and Common mistakes. Code lives in an editor panel: pick a language on its tabs once and every editor on the page switches.

Five ideas that make patterns click

Patterns are built from a few object-oriented ideas. If these are fuzzy, patterns will feel like magic. If they are clear, patterns look obvious.

Encapsulation
Keep data private and only let other code touch it through methods. This is why a Memento can hide its contents and a Singleton can hide its constructor.
Abstraction (interfaces)
Describe what something does without saying how. A Notifier interface says send(message). Email and SMS are two different hows. Almost every pattern depends on this.
Inheritance
A class gets everything its parent has. Use it for a true 'is-a' relationship (a Truck is a Vehicle). It is powerful and rigid, so use it sparingly.
Polymorphism
Code written against the interface works with any class that implements it. The caller does not know, or care, which one it gets. This is what makes Strategy, State and Factory work.
Composition over inheritance
Instead of inheriting behaviour, hold another object and call it ('has-a'). It is easier to swap and test. Decorator, Strategy, Bridge and Observer all use composition.

The SOLID principles and the patterns that serve them

SOLID is five rules of thumb for clean class design. Patterns are the common ways to follow them.

RuleIn plain wordsA smell that breaks itPatterns that help
S Single Responsibility A class should have one reason to change. A class that talks to the database, formats a report and sends email. Facade, Strategy, Observer, Visitor
O Open / Closed Add new behaviour by adding code, not by editing old code. Every new payment type means editing the same if/else block. Strategy, Decorator, Factory Method, Visitor
L Liskov Substitution A subclass must work anywhere its parent is expected. Penguin extends Bird and fly() throws an error. Template Method, Null Object, State
I Interface Segregation Keep interfaces small so no class must implement methods it does not need. A Worker interface with work() and eat() forced on a robot. Adapter, Facade, Bridge
D Dependency Inversion Depend on abstractions, not on concrete classes. OrderService creates new EmailSender() inside itself. Dependency Injection, Factory Method, Abstract Factory, Strategy

Pattern finder

Start from the problem in your design, not from the pattern name. Find the sentence that sounds like your situation.

If your design has this problemLook at
I need exactly one shared instance of somethingSingleton
I do not know which class to create until the program runsFactory Method
I need matching sets of objects (a theme, a vendor, a platform)Abstract Factory
A constructor has too many optional parametersBuilder
Copying an existing object is easier than building a new onePrototype
Creating an object is expensive and I can reuse itObject Pool
I must use a class whose interface does not match mineAdapter
A class varies in two independent directionsBridge
My data is a tree: things that contain thingsComposite
I want to add features to objects by wrapping themDecorator
A group of classes is too complicated for callers to useFacade
Millions of similar objects are using too much memoryFlyweight
I want to delay, guard, cache or log access to an objectProxy
A request should be handled by one of several handlers in turnChain of Responsibility
I need undo, a queue of actions or an action logCommand
I need to evaluate a small rule or formula languageInterpreter
I want to loop over a collection without knowing how it is storedIterator
Many objects talk to many other objects and it is getting tangledMediator
I need to save and restore an object's stateMemento
Several things must react when one thing changesObserver
Behaviour depends on status and I have a lot of if state == ...State
There are several ways to do the same job and I want to switchStrategy
The steps are the same but some details differTemplate Method
I keep adding new operations to a stable set of classesVisitor
A class creates its own dependencies and is hard to testDependency Injection
My code is full of if x != null checksNull Object

All 26 patterns

The 23 classic patterns come from the 1994 book Design Patterns by the 'Gang of Four' and fall into three groups. We add three more that you will use in nearly every LLD round. Every code example is complete and runnable, prints the same output in all five languages, and is checked automatically.

Creational patterns

How objects get created

  • SingletonMake sure a class has exactly one instance and give everyone the same way to reach it.
  • Factory MethodLet a method decide which exact class to create, so the rest of the code only deals with the general type.
  • Abstract FactoryCreate whole families of matching objects without naming their concrete classes.
  • BuilderBuild a complex object step by step, so you never need a constructor with ten confusing parameters.
  • PrototypeCreate a new object by copying an existing one instead of building it from scratch.

Structural patterns

How objects are put together

  • AdapterWrap an existing class so it fits the interface your code expects.
  • BridgeSplit a class that varies in two directions into two separate hierarchies and connect them with a reference.
  • CompositeTreat a single item and a group of items the same way, so trees of objects are easy to work with.
  • DecoratorAdd behaviour to an object by wrapping it, without changing its class and without a subclass for every combination.
  • FacadeGive a complicated group of classes one simple front door.
  • FlyweightSave memory by sharing the parts of many objects that are identical, and keeping only the differences separate.
  • ProxyPut a stand-in object in front of another one to control access to it: delay it, guard it, cache it or log it.

Behavioral patterns

How objects talk and share work

  • Chain of ResponsibilityPass a request along a line of handlers until one of them deals with it.
  • CommandTurn an action into an object, so you can store it, queue it, log it or undo it.
  • InterpreterRepresent the rules of a tiny language as classes, so you can evaluate sentences written in it.
  • IteratorWalk through a collection one item at a time without knowing how it stores its items.
  • MediatorHave objects talk through a go-between instead of directly to each other, to stop a web of connections forming.
  • MementoSave a snapshot of an object's state so you can restore it later, without exposing its internals.
  • ObserverLet objects subscribe to another object and be told automatically whenever it changes.
  • StateLet an object change its behaviour when its internal state changes, by moving each state into its own class.
  • StrategyPut each way of doing something in its own class, so you can swap them without touching the code that uses them.
  • Template MethodFix the order of steps in a base class and let subclasses fill in some of the steps.
  • VisitorAdd new operations to a group of classes without changing those classes, by sending a visitor object to each one.

Everyday extras

Not GoF, but you will use them in every LLD round

  • Object PoolKeep a set of expensive objects ready, lend them out and take them back instead of creating and destroying them each time.
  • Dependency InjectionHand a class the things it needs from outside instead of letting it create them itself.
  • Null ObjectReturn a harmless do-nothing object instead of null, so callers never need to check for 'nothing'.

Creational patterns

These five patterns are about making objects without scattering new calls everywhere. They keep the code that uses an object separate from the code that decides which object, and how it is built.

Creational

Singleton

Make sure a class has exactly one instance and give everyone the same way to reach it.

Explain it like I am new

A country has one government. No matter who asks, 'the government' means the same one, and you cannot just create a second.

The problem

Some things must exist only once: the app configuration, a logger, a connection manager. If every part of your code creates its own copy, they drift apart: one logs to a file, another to the console, and a setting changed in one place is invisible in another.

The idea

Hide the constructor so nobody can call it directly, keep the single instance inside the class, and expose one method (usually getInstance) that creates it the first time and returns the same one every time after.

Singleton class diagramClientAppConfig-instance: AppConfig-AppConfig() (private)+getInstance(): AppConfiggetInstance()
Clients never call the constructor. They ask getInstance() and always get back the same object.

See it in code

Two parts of the program ask for the configuration. The output shows it was created only once and both got the same object.

Python · main.py

class AppConfig:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            print("Config created once")
            cls._instance = super().__new__(cls)
            cls._instance.theme = "dark"
        return cls._instance


a = AppConfig()
b = AppConfig()
print("same object:", str(a is b).lower())
print("theme:", b.theme)

Java · Main.java

public class Main {
    public static void main(String[] args) {
        AppConfig a = AppConfig.getInstance();
        AppConfig b = AppConfig.getInstance();
        System.out.println("same object: " + (a == b));
        System.out.println("theme: " + b.getTheme());
    }
}

class AppConfig {
    private static AppConfig instance;
    private final String theme = "dark";

    private AppConfig() { System.out.println("Config created once"); }

    // synchronized keeps two threads from both creating one
    public static synchronized AppConfig getInstance() {
        if (instance == null) instance = new AppConfig();
        return instance;
    }

    public String getTheme() { return theme; }
}

C++ · main.cpp

#include <iostream>
#include <string>

class AppConfig {
public:
    static AppConfig& instance() {
        static AppConfig inst;  // created on first use; thread-safe since C++11
        return inst;
    }
    AppConfig(const AppConfig&) = delete;
    AppConfig& operator=(const AppConfig&) = delete;
    std::string theme = "dark";

private:
    AppConfig() { std::cout << "Config created once\n"; }
};

int main() {
    AppConfig& a = AppConfig::instance();
    AppConfig& b = AppConfig::instance();
    std::cout << "same object: " << (&a == &b ? "true" : "false") << "\n";
    std::cout << "theme: " << b.theme << "\n";
}

JavaScript · main.js

class AppConfig {
  static #instance = null;

  constructor() {
    if (AppConfig.#instance) return AppConfig.#instance;
    console.log("Config created once");
    this.theme = "dark";
    AppConfig.#instance = this;
  }
}

const a = new AppConfig();
const b = new AppConfig();
console.log("same object:", a === b);
console.log("theme:", b.theme);

Go · main.go

package main

import (
	"fmt"
	"sync"
)

type AppConfig struct{ Theme string }

var (
	instance *AppConfig
	once     sync.Once // runs the function exactly once, even across goroutines
)

func GetConfig() *AppConfig {
	once.Do(func() {
		fmt.Println("Config created once")
		instance = &AppConfig{Theme: "dark"}
	})
	return instance
}

func main() {
	a := GetConfig()
	b := GetConfig()
	fmt.Println("same object:", a == b)
	fmt.Println("theme:", b.Theme)
}
Output (identical in all five languages)
Config created once
same object: true
theme: dark

Use it when

  • Exactly one object must coordinate something shared (configuration, logger, ID generator, in-memory cache).
  • Creating the object is expensive and it is safe to share it.
  • You want one controlled access point instead of passing the object everywhere by hand.

Skip it when

  • You only want convenient global access. A Singleton is global state in disguise and makes tests hard because every test shares it.
  • The object holds per-user or per-request data. Shared mutable state across requests causes bugs.
  • You can pass the object in through a constructor instead (see Dependency Injection).

Where it shows up in LLD

  • Parking Lot: one ParkingLot manager for the whole building.
  • Elevator System: a single controller that all floors talk to.
  • Logger or Config in nearly every LLD problem.

Going deeper SDE-2 and SDE-3

  • Thread safety is the classic follow-up. Two threads can both see 'no instance yet' and each create one. Fix it with a lock (Java synchronized), double-checked locking with a volatile field, a static holder class, an enum, std::call_once or a function-local static in C++ (thread-safe since C++11), or sync.Once in Go.
  • Lazy versus eager: eager creation at class load is simple and thread safe but wastes work if the instance is never used.
  • In frameworks you rarely write Singletons by hand. A DI container (Spring, Guice) gives you singleton scope while keeping classes testable. Say that in an interview.
  • Serialization and reflection can break a Singleton in Java (deserializing makes a copy). An enum singleton is immune.

Common mistakes

  • Do not use it just to avoid passing parameters.
  • Forgetting thread safety.
  • Making the Singleton do too much: it becomes a god object.
Creational

Factory Method

Let a method decide which exact class to create, so the rest of the code only deals with the general type.

Explain it like I am new

A logistics company plans deliveries the same way every time. Whether the goods go by truck or ship depends on which regional office does the planning, and each office knows its own vehicle.

The problem

Code full of if type == 'email' ... else if type == 'sms' ... with new EmailSender() and new SmsSender() scattered everywhere. Adding a third type means hunting down every place that creates one.

The idea

Put object creation behind one method (the factory method) in a base class. Each subclass overrides it to return its own product. The shared logic calls the method and works with the product through an interface, never with a concrete class.

Factory Method class diagram<<abstract>>Logistics+plan()#createTransport(): TransportRoadLogisticsSeaLogistics<<interface>>TransportTruckShipcreates
The base class calls createTransport() but never names Truck or Ship. Each subclass picks one.

See it in code

Two logistics offices plan a delivery using the same code. Each creates its own kind of transport.

Python · main.py

from abc import ABC, abstractmethod


class Transport(ABC):
    @abstractmethod
    def deliver(self): ...


class Truck(Transport):
    def deliver(self):
        return "truck"


class Ship(Transport):
    def deliver(self):
        return "ship"


class Logistics(ABC):
    @abstractmethod
    def create_transport(self): ...  # the factory method

    def plan(self, label):
        print(f"{label} delivery: {self.create_transport().deliver()}")


class RoadLogistics(Logistics):
    def create_transport(self):
        return Truck()


class SeaLogistics(Logistics):
    def create_transport(self):
        return Ship()


RoadLogistics().plan("Road")
SeaLogistics().plan("Sea")

Java · Main.java

public class Main {
    public static void main(String[] args) {
        new RoadLogistics().plan("Road");
        new SeaLogistics().plan("Sea");
    }
}

interface Transport { String deliver(); }
class Truck implements Transport { public String deliver() { return "truck"; } }
class Ship implements Transport { public String deliver() { return "ship"; } }

abstract class Logistics {
    abstract Transport createTransport(); // the factory method

    void plan(String label) {
        System.out.println(label + " delivery: " + createTransport().deliver());
    }
}
class RoadLogistics extends Logistics { Transport createTransport() { return new Truck(); } }
class SeaLogistics extends Logistics { Transport createTransport() { return new Ship(); } }

C++ · main.cpp

#include <iostream>
#include <memory>
#include <string>

struct Transport {
    virtual ~Transport() = default;
    virtual std::string deliver() const = 0;
};
struct Truck : Transport { std::string deliver() const override { return "truck"; } };
struct Ship : Transport { std::string deliver() const override { return "ship"; } };

struct Logistics {
    virtual ~Logistics() = default;
    virtual std::unique_ptr<Transport> createTransport() const = 0;  // the factory method
    void plan(const std::string& label) const {
        std::cout << label << " delivery: " << createTransport()->deliver() << "\n";
    }
};
struct RoadLogistics : Logistics {
    std::unique_ptr<Transport> createTransport() const override { return std::make_unique<Truck>(); }
};
struct SeaLogistics : Logistics {
    std::unique_ptr<Transport> createTransport() const override { return std::make_unique<Ship>(); }
};

int main() {
    RoadLogistics().plan("Road");
    SeaLogistics().plan("Sea");
}

JavaScript · main.js

class Truck { deliver() { return "truck"; } }
class Ship { deliver() { return "ship"; } }

class Logistics {
  createTransport() { throw new Error("subclass must implement"); } // the factory method
  plan(label) { console.log(`${label} delivery: ${this.createTransport().deliver()}`); }
}
class RoadLogistics extends Logistics { createTransport() { return new Truck(); } }
class SeaLogistics extends Logistics { createTransport() { return new Ship(); } }

new RoadLogistics().plan("Road");
new SeaLogistics().plan("Sea");

Go · main.go

package main

import "fmt"

type Transport interface{ Deliver() string }
type Truck struct{}
type Ship struct{}

func (Truck) Deliver() string { return "truck" }
func (Ship) Deliver() string  { return "ship" }

// Go has no subclassing, so the "factory method" becomes an interface each creator implements.
type Logistics interface{ CreateTransport() Transport }
type RoadLogistics struct{}
type SeaLogistics struct{}

func (RoadLogistics) CreateTransport() Transport { return Truck{} }
func (SeaLogistics) CreateTransport() Transport  { return Ship{} }

func plan(l Logistics, label string) {
	fmt.Printf("%s delivery: %s\n", label, l.CreateTransport().Deliver())
}

func main() {
	plan(RoadLogistics{}, "Road")
	plan(SeaLogistics{}, "Sea")
}
Output (identical in all five languages)
Road delivery: truck
Sea delivery: ship

Use it when

  • You do not know ahead of time which concrete class you will need.
  • Subclasses should choose what to create while the shared steps stay the same.
  • You want to add a new product type without touching the code that uses products.

Skip it when

  • There is only one product type and no sign of more. A plain constructor is clearer.
  • The choice depends on data, not on a class hierarchy. A simple factory function (a switch on a string) is enough and simpler.

Where it shows up in LLD

  • Notification Service: EmailNotification, SmsNotification, PushNotification created from one place.
  • Vehicle or Shape creation in Parking Lot or Drawing app.
  • Payment methods in a Food Delivery or Ride Sharing design.

Going deeper SDE-2 and SDE-3

  • Many people say 'factory' and mean three things: Simple Factory (a static function with a switch, not a GoF pattern), Factory Method (subclasses decide) and Abstract Factory (a family of products). Interviewers like it when you name the difference.
  • Factory Method is Open/Closed in action: add a new product by adding a class, not by editing a switch.
  • It is a special case of Template Method where one step of the algorithm is 'create the object'.
  • In languages with first-class functions (JS, Python, Go) a plain function or a map from name to constructor often replaces the whole class hierarchy.

Common mistakes

  • Creating a subclass per product when a simple factory function would do.
  • Letting the factory return concrete types instead of an interface, which defeats the purpose.
Creational

Abstract Factory

Create whole families of matching objects without naming their concrete classes.

Explain it like I am new

A furniture shop sells matching sets: a modern sofa goes with a modern table, a classic sofa with a classic table. You pick the style once and every piece you get matches.

The problem

Your app needs several related objects that must belong together (a dark button must come with a dark checkbox). If the code creates each one itself, someone will eventually mix a dark button with a light checkbox.

The idea

Define a factory interface with one creation method per product (createButton, createCheckbox). Write one factory class per family (DarkFactory, LightFactory). Client code receives a factory and asks it for products, so it can never mix families.

Abstract Factory class diagram<<interface>>ThemeFactory+createButton()+createCheckbox()DarkFactoryLightFactoryDarkButtonDarkCheckboxLightButtonLightCheckbox
Each factory builds a matching set. The client holds a ThemeFactory and never sees Dark or Light.

See it in code

One function draws a screen using whatever factory it is given. Swapping the factory swaps the entire look.

Python · main.py

from abc import ABC, abstractmethod


class Button(ABC):
    @abstractmethod
    def draw(self): ...


class Checkbox(ABC):
    @abstractmethod
    def draw(self): ...


class DarkButton(Button):
    def draw(self): return "[dark] Button"


class DarkCheckbox(Checkbox):
    def draw(self): return "[dark] Checkbox"


class LightButton(Button):
    def draw(self): return "[light] Button"


class LightCheckbox(Checkbox):
    def draw(self): return "[light] Checkbox"


class ThemeFactory(ABC):
    @abstractmethod
    def create_button(self): ...

    @abstractmethod
    def create_checkbox(self): ...


class DarkFactory(ThemeFactory):
    def create_button(self): return DarkButton()
    def create_checkbox(self): return DarkCheckbox()


class LightFactory(ThemeFactory):
    def create_button(self): return LightButton()
    def create_checkbox(self): return LightCheckbox()


def render_screen(factory):  # knows nothing about dark or light
    print(factory.create_button().draw())
    print(factory.create_checkbox().draw())


render_screen(DarkFactory())
render_screen(LightFactory())

Java · Main.java

public class Main {
    static void renderScreen(ThemeFactory factory) { // knows nothing about dark or light
        System.out.println(factory.createButton().draw());
        System.out.println(factory.createCheckbox().draw());
    }

    public static void main(String[] args) {
        renderScreen(new DarkFactory());
        renderScreen(new LightFactory());
    }
}

interface Button { String draw(); }
interface Checkbox { String draw(); }

class DarkButton implements Button { public String draw() { return "[dark] Button"; } }
class DarkCheckbox implements Checkbox { public String draw() { return "[dark] Checkbox"; } }
class LightButton implements Button { public String draw() { return "[light] Button"; } }
class LightCheckbox implements Checkbox { public String draw() { return "[light] Checkbox"; } }

interface ThemeFactory {
    Button createButton();
    Checkbox createCheckbox();
}
class DarkFactory implements ThemeFactory {
    public Button createButton() { return new DarkButton(); }
    public Checkbox createCheckbox() { return new DarkCheckbox(); }
}
class LightFactory implements ThemeFactory {
    public Button createButton() { return new LightButton(); }
    public Checkbox createCheckbox() { return new LightCheckbox(); }
}

C++ · main.cpp

#include <iostream>
#include <memory>
#include <string>

struct Button { virtual ~Button() = default; virtual std::string draw() const = 0; };
struct Checkbox { virtual ~Checkbox() = default; virtual std::string draw() const = 0; };

struct DarkButton : Button { std::string draw() const override { return "[dark] Button"; } };
struct DarkCheckbox : Checkbox { std::string draw() const override { return "[dark] Checkbox"; } };
struct LightButton : Button { std::string draw() const override { return "[light] Button"; } };
struct LightCheckbox : Checkbox { std::string draw() const override { return "[light] Checkbox"; } };

struct ThemeFactory {
    virtual ~ThemeFactory() = default;
    virtual std::unique_ptr<Button> createButton() const = 0;
    virtual std::unique_ptr<Checkbox> createCheckbox() const = 0;
};
struct DarkFactory : ThemeFactory {
    std::unique_ptr<Button> createButton() const override { return std::make_unique<DarkButton>(); }
    std::unique_ptr<Checkbox> createCheckbox() const override { return std::make_unique<DarkCheckbox>(); }
};
struct LightFactory : ThemeFactory {
    std::unique_ptr<Button> createButton() const override { return std::make_unique<LightButton>(); }
    std::unique_ptr<Checkbox> createCheckbox() const override { return std::make_unique<LightCheckbox>(); }
};

void renderScreen(const ThemeFactory& factory) {  // knows nothing about dark or light
    std::cout << factory.createButton()->draw() << "\n";
    std::cout << factory.createCheckbox()->draw() << "\n";
}

int main() {
    renderScreen(DarkFactory());
    renderScreen(LightFactory());
}

JavaScript · main.js

class DarkButton { draw() { return "[dark] Button"; } }
class DarkCheckbox { draw() { return "[dark] Checkbox"; } }
class LightButton { draw() { return "[light] Button"; } }
class LightCheckbox { draw() { return "[light] Checkbox"; } }

class DarkFactory {
  createButton() { return new DarkButton(); }
  createCheckbox() { return new DarkCheckbox(); }
}
class LightFactory {
  createButton() { return new LightButton(); }
  createCheckbox() { return new LightCheckbox(); }
}

function renderScreen(factory) { // knows nothing about dark or light
  console.log(factory.createButton().draw());
  console.log(factory.createCheckbox().draw());
}

renderScreen(new DarkFactory());
renderScreen(new LightFactory());

Go · main.go

package main

import "fmt"

type Button interface{ Draw() string }
type Checkbox interface{ Draw() string }

type DarkButton struct{}
type DarkCheckbox struct{}
type LightButton struct{}
type LightCheckbox struct{}

func (DarkButton) Draw() string    { return "[dark] Button" }
func (DarkCheckbox) Draw() string  { return "[dark] Checkbox" }
func (LightButton) Draw() string   { return "[light] Button" }
func (LightCheckbox) Draw() string { return "[light] Checkbox" }

type ThemeFactory interface {
	CreateButton() Button
	CreateCheckbox() Checkbox
}

type DarkFactory struct{}
type LightFactory struct{}

func (DarkFactory) CreateButton() Button      { return DarkButton{} }
func (DarkFactory) CreateCheckbox() Checkbox  { return DarkCheckbox{} }
func (LightFactory) CreateButton() Button     { return LightButton{} }
func (LightFactory) CreateCheckbox() Checkbox { return LightCheckbox{} }

func renderScreen(f ThemeFactory) { // knows nothing about dark or light
	fmt.Println(f.CreateButton().Draw())
	fmt.Println(f.CreateCheckbox().Draw())
}

func main() {
	renderScreen(DarkFactory{})
	renderScreen(LightFactory{})
}
Output (identical in all five languages)
[dark] Button
[dark] Checkbox
[light] Button
[light] Checkbox

Use it when

  • Products come in families that must be used together (themes, operating systems, database vendors, regions).
  • You want to switch the whole family by swapping one object.
  • Client code should not depend on concrete product classes.

Skip it when

  • There is one product, not a family. Use Factory Method.
  • Families rarely change. The extra interfaces cost more than they save.

Where it shows up in LLD

  • Cross-platform UI toolkit (Windows, Mac, Linux widgets).
  • Database layer that can target MySQL or Postgres (connection, command, reader).
  • Game: forest vs desert level with matching enemies, terrain and items.

Going deeper SDE-2 and SDE-3

  • The weak spot: adding a new product type (a Slider) means changing the factory interface and every factory. Adding a new family is easy, adding a new product is hard. Mention this trade-off.
  • Often implemented with Factory Methods inside each factory, and the factory itself is often a Singleton.
  • With dependency injection you wire the correct factory once at startup and the rest of the code never knows which family it is in.

Common mistakes

  • Using it when a plain Factory Method is enough.
  • Letting client code create a concrete factory in many places instead of once.
Creational

Builder

Build a complex object step by step, so you never need a constructor with ten confusing parameters.

Explain it like I am new

Ordering a pizza: you start with a size, then say yes or no to each topping, and only at the end the kitchen makes it. You never hand over one giant order form with every field filled in.

The problem

A class with many optional settings ends up with constructors like new Pizza(true, false, true, false, 12, null). Nobody can read that, and you either write dozens of constructor versions or pass lots of nulls.

The idea

Create a separate Builder class that collects the settings one named method at a time (.pepperoni(), .mushrooms()) and has a final build() that creates the finished object. Each setting is clear at the call site, the finished object can be immutable, and build() can check everything is valid.

Builder class diagramClientPizzaBuilder+pepperoni(): PizzaBuilder+mushrooms(): PizzaBuilder+build(): PizzaPizza(immutable)chain callsbuild()
The client chains named steps on the builder; build() produces the finished, ready-to-use object.

See it in code

Two pizzas are made with the same builder: one loaded with toppings, one plain.

Python · main.py

class Pizza:
    def __init__(self, size, cheese, pepperoni, mushrooms):
        self.size, self.cheese, self.pepperoni, self.mushrooms = size, cheese, pepperoni, mushrooms

    def __str__(self):
        flag = lambda v: str(v).lower()
        return (f"Pizza(size={self.size}, cheese={flag(self.cheese)}, "
                f"pepperoni={flag(self.pepperoni)}, mushrooms={flag(self.mushrooms)})")


class PizzaBuilder:
    def __init__(self, size):
        self._size, self._cheese, self._pepperoni, self._mushrooms = size, True, False, False

    def pepperoni(self):
        self._pepperoni = True
        return self  # returning self lets calls chain

    def mushrooms(self):
        self._mushrooms = True
        return self

    def build(self):
        return Pizza(self._size, self._cheese, self._pepperoni, self._mushrooms)


print(PizzaBuilder("large").pepperoni().build())
print(PizzaBuilder("small").build())

Java · Main.java

public class Main {
    public static void main(String[] args) {
        System.out.println(new Pizza.Builder("large").pepperoni().build());
        System.out.println(new Pizza.Builder("small").build());
    }
}

class Pizza {
    private final String size;
    private final boolean cheese, pepperoni, mushrooms;

    private Pizza(Builder b) { size = b.size; cheese = b.cheese; pepperoni = b.pepperoni; mushrooms = b.mushrooms; }

    @Override public String toString() {
        return "Pizza(size=" + size + ", cheese=" + cheese + ", pepperoni=" + pepperoni + ", mushrooms=" + mushrooms + ")";
    }

    static class Builder {
        private final String size;
        private boolean cheese = true, pepperoni = false, mushrooms = false;

        Builder(String size) { this.size = size; }
        Builder pepperoni() { pepperoni = true; return this; } // returning this lets calls chain
        Builder mushrooms() { mushrooms = true; return this; }
        Pizza build() { return new Pizza(this); }
    }
}

C++ · main.cpp

#include <iostream>
#include <string>

class Pizza {
public:
    class Builder;
    std::string str() const {
        auto flag = [](bool v) { return v ? "true" : "false"; };
        return "Pizza(size=" + size + ", cheese=" + flag(cheese) + ", pepperoni=" + flag(pepperoni) +
               ", mushrooms=" + flag(mushrooms) + ")";
    }

private:
    Pizza(std::string s, bool c, bool p, bool m) : size(s), cheese(c), pepperoni(p), mushrooms(m) {}
    std::string size;
    bool cheese, pepperoni, mushrooms;
};

class Pizza::Builder {
public:
    explicit Builder(std::string size) : size_(size) {}
    Builder& pepperoni() { pepperoni_ = true; return *this; }  // returning *this lets calls chain
    Builder& mushrooms() { mushrooms_ = true; return *this; }
    Pizza build() const { return Pizza(size_, cheese_, pepperoni_, mushrooms_); }

private:
    std::string size_;
    bool cheese_ = true, pepperoni_ = false, mushrooms_ = false;
};

int main() {
    std::cout << Pizza::Builder("large").pepperoni().build().str() << "\n";
    std::cout << Pizza::Builder("small").build().str() << "\n";
}

JavaScript · main.js

class Pizza {
  constructor(size, cheese, pepperoni, mushrooms) {
    Object.assign(this, { size, cheese, pepperoni, mushrooms });
    Object.freeze(this); // immutable once built
  }
  toString() {
    return `Pizza(size=${this.size}, cheese=${this.cheese}, pepperoni=${this.pepperoni}, mushrooms=${this.mushrooms})`;
  }
}

class PizzaBuilder {
  constructor(size) { this.size = size; this.cheese = true; this.hasPepperoni = false; this.hasMushrooms = false; }
  pepperoni() { this.hasPepperoni = true; return this; } // returning this lets calls chain
  mushrooms() { this.hasMushrooms = true; return this; }
  build() { return new Pizza(this.size, this.cheese, this.hasPepperoni, this.hasMushrooms); }
}

console.log(String(new PizzaBuilder("large").pepperoni().build()));
console.log(String(new PizzaBuilder("small").build()));

Go · main.go

package main

import "fmt"

type Pizza struct {
	size                          string
	cheese, pepperoni, mushrooms bool
}

func (p Pizza) String() string {
	return fmt.Sprintf("Pizza(size=%s, cheese=%t, pepperoni=%t, mushrooms=%t)", p.size, p.cheese, p.pepperoni, p.mushrooms)
}

type PizzaBuilder struct{ p Pizza }

func NewPizzaBuilder(size string) *PizzaBuilder {
	return &PizzaBuilder{Pizza{size: size, cheese: true}}
}

func (b *PizzaBuilder) Pepperoni() *PizzaBuilder { b.p.pepperoni = true; return b } // returning b lets calls chain
func (b *PizzaBuilder) Mushrooms() *PizzaBuilder { b.p.mushrooms = true; return b }
func (b *PizzaBuilder) Build() Pizza             { return b.p }

func main() {
	fmt.Println(NewPizzaBuilder("large").Pepperoni().Build())
	fmt.Println(NewPizzaBuilder("small").Build())
}
Output (identical in all five languages)
Pizza(size=large, cheese=true, pepperoni=true, mushrooms=false)
Pizza(size=small, cheese=true, pepperoni=false, mushrooms=false)

Use it when

  • An object has many optional parameters.
  • You want an immutable object that is still easy to create.
  • Construction has steps or validation rules (for example, an HTTP request must have a URL).

Skip it when

  • The object has two or three required fields. A constructor is simpler.
  • Your language has named and default arguments (Python, Kotlin) and that already reads well.

Where it shows up in LLD

  • Building a Pizza, Burger or Meal in a Food Ordering system.
  • Constructing a Chess or Tic-Tac-Toe board with configurable size and rules.
  • An HTTP request or SQL query object.

Going deeper SDE-2 and SDE-3

  • The GoF version has a Director class that knows the order of steps to build common recipes (a 'Margherita' recipe). In practice most code skips the Director and uses a fluent builder.
  • Make the target class's constructor private and let only the Builder call it. Then objects can only be created validly.
  • Compare with Telescoping Constructors and JavaBeans setters: the first is unreadable, the second leaves half-built, mutable objects. Builder fixes both.
  • In Go the equivalent is the functional options pattern: NewServer(WithPort(80), WithTLS()).

Common mistakes

  • Forgetting to validate in build().
  • Builder that mutates and is reused, so two objects share state.
Creational

Prototype

Create a new object by copying an existing one instead of building it from scratch.

Explain it like I am new

You photocopy a filled-in form, then change just the name on the copy. You do not retype the whole form, and scribbling on the copy does not change the original.

The problem

Creating some objects is slow or complicated (loaded from a database, parsed from a file, configured through many steps). You often need many near-identical objects that differ in one or two fields.

The idea

Give the object a clone() method that returns an independent copy of itself. Callers copy a ready-made prototype and tweak the copy. The key detail is a deep copy: nested lists and objects must be duplicated too, otherwise the copy and the original secretly share them.

Prototype class diagram<<interface>>Prototype+clone(): PrototypeReportClientclone()
The client holds something cloneable, calls clone() and gets an independent copy to modify.

See it in code

A report is copied, the copy gets a new title and an extra page, and the original stays untouched.

Python · main.py

import copy


class Report:
    def __init__(self, title, pages):
        self.title, self.pages = title, pages

    def clone(self):
        return copy.deepcopy(self)  # deep: the pages list is copied too

    def __str__(self):
        return f"{self.title} ({len(self.pages)} pages)"


original = Report("Q1", [1, 2])
duplicate = original.clone()
duplicate.title = "Q1 copy"
duplicate.pages.append(3)

print("original:", original)
print("copy:", duplicate)
print("original:", original)

Java · Main.java

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

public class Main {
    public static void main(String[] args) {
        Report original = new Report("Q1", new ArrayList<>(List.of(1, 2)));
        Report copy = original.copy();
        copy.title = "Q1 copy";
        copy.pages.add(3);

        System.out.println("original: " + original);
        System.out.println("copy: " + copy);
        System.out.println("original: " + original);
    }
}

class Report {
    String title;
    List<Integer> pages;

    Report(String title, List<Integer> pages) { this.title = title; this.pages = pages; }

    Report copy() { return new Report(title, new ArrayList<>(pages)); } // deep: new list, not the same one

    @Override public String toString() { return title + " (" + pages.size() + " pages)"; }
}

C++ · main.cpp

#include <iostream>
#include <string>
#include <vector>

struct Report {
    std::string title;
    std::vector<int> pages;

    // The compiler-made copy constructor already copies the vector deeply.
    Report clone() const { return *this; }
    std::string str() const { return title + " (" + std::to_string(pages.size()) + " pages)"; }
};

int main() {
    Report original{"Q1", {1, 2}};
    Report copy = original.clone();
    copy.title = "Q1 copy";
    copy.pages.push_back(3);

    std::cout << "original: " << original.str() << "\n";
    std::cout << "copy: " << copy.str() << "\n";
    std::cout << "original: " << original.str() << "\n";
}

JavaScript · main.js

class Report {
  constructor(title, pages) { this.title = title; this.pages = pages; }
  clone() { return new Report(this.title, structuredClone(this.pages)); } // deep copy of the array
  toString() { return `${this.title} (${this.pages.length} pages)`; }
}

const original = new Report("Q1", [1, 2]);
const copy = original.clone();
copy.title = "Q1 copy";
copy.pages.push(3);

console.log("original:", String(original));
console.log("copy:", String(copy));
console.log("original:", String(original));

Go · main.go

package main

import "fmt"

type Report struct {
	Title string
	Pages []int
}

// Clone copies the slice too. Assigning a struct copies only the slice header,
// so both values would still point at the same backing array.
func (r Report) Clone() Report {
	pages := make([]int, len(r.Pages))
	copy(pages, r.Pages)
	return Report{r.Title, pages}
}

func (r Report) String() string { return fmt.Sprintf("%s (%d pages)", r.Title, len(r.Pages)) }

func main() {
	original := Report{"Q1", []int{1, 2}}
	dup := original.Clone()
	dup.Title = "Q1 copy"
	dup.Pages = append(dup.Pages, 3)

	fmt.Println("original:", original)
	fmt.Println("copy:", dup)
	fmt.Println("original:", original)
}
Output (identical in all five languages)
original: Q1 (2 pages)
copy: Q1 copy (3 pages)
original: Q1 (2 pages)

Use it when

  • Building an object is expensive and you need many similar ones.
  • You want copies without knowing their concrete class (you only hold the interface).
  • You keep a registry of ready-to-clone templates (game enemies, document templates).

Skip it when

  • Objects are cheap to create from scratch.
  • The object holds resources that cannot be copied (open files, sockets, threads).

Where it shows up in LLD

  • Document or Spreadsheet templates ('duplicate this sheet').
  • Game units: clone a configured enemy 100 times.
  • Chess: copy the board to try a move and undo it (also used with Memento).

Going deeper SDE-2 and SDE-3

  • Shallow versus deep copy is the whole interview question. A shallow copy duplicates only the top level, so a list inside is shared and changing it changes both objects.
  • Language support: Python copy.deepcopy, Java Cloneable is widely considered broken so prefer a copy constructor, C++ copy constructors do this natively, JS structuredClone, Go copies structs by value but slices and maps stay shared.
  • Prototype pairs with a registry (a map from name to prototype), which is a light alternative to Factory Method.
  • Cyclic references need care: a naive deep copy can loop forever.

Common mistakes

  • Shallow copies that share mutable state.
  • Forgetting to reset identity fields (ID, created time) on the copy.

Structural patterns

These seven patterns are about how classes and objects fit together into larger structures: wrapping, sharing, and hiding complexity, while keeping the pieces flexible.

Structural

Adapter

Wrap an existing class so it fits the interface your code expects.

Explain it like I am new

A travel plug adapter. Your laptop charger has a two-pin plug, the wall socket in another country is different. The adapter does not change either one, it just sits between them.

The problem

You have working code that expects one interface (pay(rupees)), and a library or legacy class you cannot change that does the same job through a different one (charge_paise(paise)). Rewriting either side is risky or impossible.

The idea

Write a small Adapter class that implements the interface your code expects and holds the incompatible object inside. Each call is translated and forwarded. The rest of your system never learns the old class exists.

Adapter class diagramCheckout<<interface>>PaymentProcessor+pay(rupees)GatewayAdapterOldGateway+chargePaise(paise)useswraps
Checkout talks to PaymentProcessor. The adapter implements it and translates each call for the old gateway.

See it in code

The checkout code only knows about rupees. The adapter converts to the legacy gateway's paise.

Python · main.py

class OldGateway:  # third-party code we cannot change
    def charge_paise(self, paise):
        print(f"Gateway charged {paise} paise")


class PaymentProcessor:  # the interface our app expects
    def pay(self, rupees):
        raise NotImplementedError


class GatewayAdapter(PaymentProcessor):
    def __init__(self, gateway):
        self._gateway = gateway

    def pay(self, rupees):
        self._gateway.charge_paise(rupees * 100)  # translate rupees to paise


def checkout(processor):
    processor.pay(499)
    processor.pay(10)


checkout(GatewayAdapter(OldGateway()))

Java · Main.java

public class Main {
    static void checkout(PaymentProcessor processor) {
        processor.pay(499);
        processor.pay(10);
    }

    public static void main(String[] args) {
        checkout(new GatewayAdapter(new OldGateway()));
    }
}

class OldGateway { // third-party code we cannot change
    void chargePaise(int paise) { System.out.println("Gateway charged " + paise + " paise"); }
}

interface PaymentProcessor { void pay(int rupees); } // the interface our app expects

class GatewayAdapter implements PaymentProcessor {
    private final OldGateway gateway;

    GatewayAdapter(OldGateway gateway) { this.gateway = gateway; }

    public void pay(int rupees) { gateway.chargePaise(rupees * 100); } // translate rupees to paise
}

C++ · main.cpp

#include <iostream>

struct OldGateway {  // third-party code we cannot change
    void chargePaise(int paise) { std::cout << "Gateway charged " << paise << " paise\n"; }
};

struct PaymentProcessor {  // the interface our app expects
    virtual ~PaymentProcessor() = default;
    virtual void pay(int rupees) = 0;
};

class GatewayAdapter : public PaymentProcessor {
public:
    explicit GatewayAdapter(OldGateway& g) : gateway_(g) {}
    void pay(int rupees) override { gateway_.chargePaise(rupees * 100); }  // translate rupees to paise

private:
    OldGateway& gateway_;
};

void checkout(PaymentProcessor& processor) {
    processor.pay(499);
    processor.pay(10);
}

int main() {
    OldGateway gateway;
    GatewayAdapter adapter(gateway);
    checkout(adapter);
}

JavaScript · main.js

class OldGateway { // third-party code we cannot change
  chargePaise(paise) { console.log(`Gateway charged ${paise} paise`); }
}

class GatewayAdapter { // offers the pay(rupees) our app expects
  constructor(gateway) { this.gateway = gateway; }
  pay(rupees) { this.gateway.chargePaise(rupees * 100); } // translate rupees to paise
}

function checkout(processor) {
  processor.pay(499);
  processor.pay(10);
}

checkout(new GatewayAdapter(new OldGateway()));

Go · main.go

package main

import "fmt"

type OldGateway struct{} // third-party code we cannot change

func (OldGateway) ChargePaise(paise int) { fmt.Printf("Gateway charged %d paise\n", paise) }

type PaymentProcessor interface{ Pay(rupees int) } // the interface our app expects

type GatewayAdapter struct{ gateway OldGateway }

func (a GatewayAdapter) Pay(rupees int) { a.gateway.ChargePaise(rupees * 100) } // rupees to paise

func checkout(p PaymentProcessor) {
	p.Pay(499)
	p.Pay(10)
}

func main() {
	checkout(GatewayAdapter{OldGateway{}})
}
Output (identical in all five languages)
Gateway charged 49900 paise
Gateway charged 1000 paise

Use it when

  • You must use a third-party SDK or legacy class whose interface does not match yours.
  • You are migrating from one library to another and want to switch gradually.
  • You want several incompatible classes to look the same to the rest of your code.

Skip it when

  • You own both sides. Just change the interface.
  • The mismatch is huge and the adapter would contain real business logic. That is a new service, not an adapter.

Where it shows up in LLD

  • Payment system: wrap Stripe, Razorpay and PayPal SDKs behind one PaymentProcessor.
  • Notification system: wrap different SMS or email vendors.
  • Logging: adapt a third-party logger to your Logger interface.

Going deeper SDE-2 and SDE-3

  • Object adapter (holds the adaptee, shown here) is preferred over class adapter (inherits from the adaptee) because it works with composition and across languages without multiple inheritance.
  • Adapter changes an interface without adding behaviour. Decorator keeps the same interface and adds behaviour. Facade offers a new simpler interface to many classes. Interviewers love asking you to tell these three apart.
  • Hexagonal architecture is Adapter at system scale: ports (your interfaces) and adapters (database, HTTP, queue).
  • Watch units, error handling and exceptions in the translation. Most adapter bugs are the conversion, such as rupees versus paise.

Common mistakes

  • Putting business rules in the adapter.
  • Leaking the adaptee's types or exceptions through the adapter.
Structural

Bridge

Split a class that varies in two directions into two separate hierarchies and connect them with a reference.

Explain it like I am new

A TV remote and a TV. You can make many kinds of remotes (basic, voice) and many kinds of TVs (Sony, Samsung) and any remote works with any TV because they only agree on a small interface.

The problem

Shapes can be circles or squares, and they can be drawn as vectors or as pixels. Subclassing gives VectorCircle, RasterCircle, VectorSquare, RasterSquare. Add triangles and a new renderer and you now have 6 classes, then 9, then 12.

The idea

Separate the two ideas. The Shape hierarchy (what to draw) holds a reference to a Renderer (how to draw). Each hierarchy grows on its own: 2 shapes + 2 renderers = 4 classes, and adding one more of either adds just one class.

Bridge class diagram<<abstract>>Shape-renderer: Renderer+draw()CircleSquare<<interface>>Renderer+drawCircle(r)+drawSquare(s)VectorRendererRasterRendererbridge
Shape (what) and Renderer (how) grow separately. The reference between them is the bridge.

See it in code

Two shapes and two renderers are combined freely: four outputs from four classes (not eight).

Python · main.py

from abc import ABC, abstractmethod


class Renderer(ABC):
    @abstractmethod
    def draw_circle(self, radius): ...

    @abstractmethod
    def draw_square(self, side): ...


class VectorRenderer(Renderer):
    def draw_circle(self, radius): print(f"Drawing circle of radius {radius} as vector")
    def draw_square(self, side): print(f"Drawing square of side {side} as vector")


class RasterRenderer(Renderer):
    def draw_circle(self, radius): print(f"Drawing circle of radius {radius} as pixels")
    def draw_square(self, side): print(f"Drawing square of side {side} as pixels")


class Shape(ABC):
    def __init__(self, renderer):
        self.renderer = renderer  # the bridge

    @abstractmethod
    def draw(self): ...


class Circle(Shape):
    def draw(self): self.renderer.draw_circle(5)


class Square(Shape):
    def draw(self): self.renderer.draw_square(3)


for shape_cls in (Circle, Square):
    for renderer in (VectorRenderer(), RasterRenderer()):
        shape_cls(renderer).draw()

Java · Main.java

public class Main {
    public static void main(String[] args) {
        Renderer[] renderers = { new VectorRenderer(), new RasterRenderer() };
        for (Renderer r : renderers) new Circle(r).draw();
        for (Renderer r : renderers) new Square(r).draw();
    }
}

interface Renderer {
    void drawCircle(int radius);
    void drawSquare(int side);
}
class VectorRenderer implements Renderer {
    public void drawCircle(int r) { System.out.println("Drawing circle of radius " + r + " as vector"); }
    public void drawSquare(int s) { System.out.println("Drawing square of side " + s + " as vector"); }
}
class RasterRenderer implements Renderer {
    public void drawCircle(int r) { System.out.println("Drawing circle of radius " + r + " as pixels"); }
    public void drawSquare(int s) { System.out.println("Drawing square of side " + s + " as pixels"); }
}

abstract class Shape {
    protected final Renderer renderer; // the bridge
    Shape(Renderer renderer) { this.renderer = renderer; }
    abstract void draw();
}
class Circle extends Shape {
    Circle(Renderer r) { super(r); }
    void draw() { renderer.drawCircle(5); }
}
class Square extends Shape {
    Square(Renderer r) { super(r); }
    void draw() { renderer.drawSquare(3); }
}

C++ · main.cpp

#include <iostream>
#include <memory>
#include <vector>

struct Renderer {
    virtual ~Renderer() = default;
    virtual void drawCircle(int radius) const = 0;
    virtual void drawSquare(int side) const = 0;
};
struct VectorRenderer : Renderer {
    void drawCircle(int r) const override { std::cout << "Drawing circle of radius " << r << " as vector\n"; }
    void drawSquare(int s) const override { std::cout << "Drawing square of side " << s << " as vector\n"; }
};
struct RasterRenderer : Renderer {
    void drawCircle(int r) const override { std::cout << "Drawing circle of radius " << r << " as pixels\n"; }
    void drawSquare(int s) const override { std::cout << "Drawing square of side " << s << " as pixels\n"; }
};

class Shape {
public:
    explicit Shape(const Renderer& r) : renderer(r) {}  // the bridge
    virtual ~Shape() = default;
    virtual void draw() const = 0;

protected:
    const Renderer& renderer;
};
struct Circle : Shape {
    using Shape::Shape;
    void draw() const override { renderer.drawCircle(5); }
};
struct Square : Shape {
    using Shape::Shape;
    void draw() const override { renderer.drawSquare(3); }
};

int main() {
    VectorRenderer vector;
    RasterRenderer raster;
    for (const Renderer* r : {static_cast<const Renderer*>(&vector), static_cast<const Renderer*>(&raster)})
        Circle(*r).draw();
    for (const Renderer* r : {static_cast<const Renderer*>(&vector), static_cast<const Renderer*>(&raster)})
        Square(*r).draw();
}

JavaScript · main.js

class VectorRenderer {
  drawCircle(r) { console.log(`Drawing circle of radius ${r} as vector`); }
  drawSquare(s) { console.log(`Drawing square of side ${s} as vector`); }
}
class RasterRenderer {
  drawCircle(r) { console.log(`Drawing circle of radius ${r} as pixels`); }
  drawSquare(s) { console.log(`Drawing square of side ${s} as pixels`); }
}

class Shape {
  constructor(renderer) { this.renderer = renderer; } // the bridge
}
class Circle extends Shape { draw() { this.renderer.drawCircle(5); } }
class Square extends Shape { draw() { this.renderer.drawSquare(3); } }

const renderers = [new VectorRenderer(), new RasterRenderer()];
for (const ShapeClass of [Circle, Square]) {
  for (const r of renderers) new ShapeClass(r).draw();
}

Go · main.go

package main

import "fmt"

type Renderer interface {
	DrawCircle(radius int)
	DrawSquare(side int)
}

type VectorRenderer struct{}
type RasterRenderer struct{}

func (VectorRenderer) DrawCircle(r int) { fmt.Printf("Drawing circle of radius %d as vector\n", r) }
func (VectorRenderer) DrawSquare(s int) { fmt.Printf("Drawing square of side %d as vector\n", s) }
func (RasterRenderer) DrawCircle(r int) { fmt.Printf("Drawing circle of radius %d as pixels\n", r) }
func (RasterRenderer) DrawSquare(s int) { fmt.Printf("Drawing square of side %d as pixels\n", s) }

type Shape interface{ Draw() }

type Circle struct{ renderer Renderer } // the bridge is the renderer field
type Square struct{ renderer Renderer }

func (c Circle) Draw() { c.renderer.DrawCircle(5) }
func (s Square) Draw() { s.renderer.DrawSquare(3) }

func main() {
	renderers := []Renderer{VectorRenderer{}, RasterRenderer{}}
	for _, r := range renderers {
		Circle{r}.Draw()
	}
	for _, r := range renderers {
		Square{r}.Draw()
	}
}
Output (identical in all five languages)
Drawing circle of radius 5 as vector
Drawing circle of radius 5 as pixels
Drawing square of side 3 as vector
Drawing square of side 3 as pixels

Use it when

  • A class varies along two independent dimensions (shape and renderer, device and remote, message and channel).
  • You want to switch the implementation at runtime.
  • You see a hierarchy exploding into combinations.

Skip it when

  • There is only one dimension of change. Plain inheritance or Strategy is simpler.
  • The two sides are tightly coupled by nature.

Where it shows up in LLD

  • Notification system: message type (alert, promo) × channel (email, SMS, push).
  • Drawing app: shape × renderer.
  • Remote control × device in a Smart Home design.

Going deeper SDE-2 and SDE-3

  • Bridge looks like Strategy (an object holding a reference to an interface), but the intent differs. Strategy swaps one algorithm inside a class. Bridge is a design decision made up front to keep two whole hierarchies independent.
  • Compare with Adapter: Adapter fixes a mismatch after the fact, Bridge prevents the mismatch by design.
  • The reference from abstraction to implementation is the 'bridge'. Prefer composition over inheritance is the principle behind it.
  • Abstraction and implementation here are design terms, not Java's abstract keyword.

Common mistakes

  • Using it when only one dimension varies.
  • Making the implementation interface too wide and leaky.
Structural

Composite

Treat a single item and a group of items the same way, so trees of objects are easy to work with.

Explain it like I am new

Files and folders. You can ask a file for its size, and you can ask a folder for its size. The folder just adds up what is inside, including other folders, and you never need to care which is which.

The problem

You have things that contain other things (folders in folders, menus in menus, an org chart). Without a common interface, every caller needs if it is a folder, loop over children, else ... everywhere.

The idea

Give leaves (File) and containers (Folder) the same interface. A leaf does the work itself. A container holds a list of that same interface and forwards the call to each child, combining the results. Callers just call the method.

Composite class diagram<<interface>>Node+size(): int+print(indent)FileFolder-children: List<Node>0..*
A Folder is a Node that holds more Nodes. Calling size() on the top node walks the whole tree.

See it in code

A folder tree prints itself. Each folder's size is the sum of everything inside it.

Python · main.py

from abc import ABC, abstractmethod


class Node(ABC):
    @abstractmethod
    def size(self): ...

    @abstractmethod
    def show(self, indent=0): ...


class File(Node):
    def __init__(self, name, kb):
        self.name, self.kb = name, kb

    def size(self):
        return self.kb

    def show(self, indent=0):
        print(" " * indent + f"{self.name} ({self.size()} KB)")


class Folder(Node):
    def __init__(self, name, children):
        self.name, self.children = name, children

    def size(self):
        return sum(child.size() for child in self.children)  # the same call on every child

    def show(self, indent=0):
        print(" " * indent + f"{self.name} ({self.size()} KB)")
        for child in self.children:
            child.show(indent + 2)


root = Folder("root", [
    File("photo.jpg", 300),
    File("notes.txt", 20),
    Folder("docs", [File("a.pdf", 100), File("b.pdf", 150)]),
])
root.show()

Java · Main.java

import java.util.List;

public class Main {
    public static void main(String[] args) {
        Node root = new Folder("root", List.of(
            new FileNode("photo.jpg", 300),
            new FileNode("notes.txt", 20),
            new Folder("docs", List.of(new FileNode("a.pdf", 100), new FileNode("b.pdf", 150)))));
        root.show(0);
    }
}

interface Node {
    int size();
    void show(int indent);
}

class FileNode implements Node {
    private final String name;
    private final int kb;
    FileNode(String name, int kb) { this.name = name; this.kb = kb; }
    public int size() { return kb; }
    public void show(int indent) { System.out.println(" ".repeat(indent) + name + " (" + size() + " KB)"); }
}

class Folder implements Node {
    private final String name;
    private final List<Node> children;
    Folder(String name, List<Node> children) { this.name = name; this.children = children; }

    public int size() {
        int total = 0;
        for (Node child : children) total += child.size(); // the same call on every child
        return total;
    }

    public void show(int indent) {
        System.out.println(" ".repeat(indent) + name + " (" + size() + " KB)");
        for (Node child : children) child.show(indent + 2);
    }
}

C++ · main.cpp

#include <iostream>
#include <memory>
#include <string>
#include <vector>

struct Node {
    virtual ~Node() = default;
    virtual int size() const = 0;
    virtual void show(int indent = 0) const = 0;
};

struct File : Node {
    std::string name;
    int kb;
    File(std::string n, int k) : name(std::move(n)), kb(k) {}
    int size() const override { return kb; }
    void show(int indent = 0) const override {
        std::cout << std::string(indent, ' ') << name << " (" << size() << " KB)\n";
    }
};

struct Folder : Node {
    std::string name;
    std::vector<std::unique_ptr<Node>> children;
    explicit Folder(std::string n) : name(std::move(n)) {}
    Folder& add(std::unique_ptr<Node> child) { children.push_back(std::move(child)); return *this; }

    int size() const override {
        int total = 0;
        for (const auto& c : children) total += c->size();  // the same call on every child
        return total;
    }
    void show(int indent = 0) const override {
        std::cout << std::string(indent, ' ') << name << " (" << size() << " KB)\n";
        for (const auto& c : children) c->show(indent + 2);
    }
};

int main() {
    auto docs = std::make_unique<Folder>("docs");
    docs->add(std::make_unique<File>("a.pdf", 100)).add(std::make_unique<File>("b.pdf", 150));

    Folder root("root");
    root.add(std::make_unique<File>("photo.jpg", 300))
        .add(std::make_unique<File>("notes.txt", 20))
        .add(std::move(docs));
    root.show();
}

JavaScript · main.js

class File {
  constructor(name, kb) { this.name = name; this.kb = kb; }
  size() { return this.kb; }
  show(indent = 0) { console.log(" ".repeat(indent) + `${this.name} (${this.size()} KB)`); }
}

class Folder {
  constructor(name, children) { this.name = name; this.children = children; }
  size() { return this.children.reduce((sum, child) => sum + child.size(), 0); } // same call on every child
  show(indent = 0) {
    console.log(" ".repeat(indent) + `${this.name} (${this.size()} KB)`);
    for (const child of this.children) child.show(indent + 2);
  }
}

const root = new Folder("root", [
  new File("photo.jpg", 300),
  new File("notes.txt", 20),
  new Folder("docs", [new File("a.pdf", 100), new File("b.pdf", 150)]),
]);
root.show();

Go · main.go

package main

import (
	"fmt"
	"strings"
)

type Node interface {
	Size() int
	Show(indent int)
}

type File struct {
	Name string
	KB   int
}

func (f File) Size() int { return f.KB }
func (f File) Show(indent int) {
	fmt.Printf("%s%s (%d KB)\n", strings.Repeat(" ", indent), f.Name, f.Size())
}

type Folder struct {
	Name     string
	Children []Node
}

func (d Folder) Size() int {
	total := 0
	for _, c := range d.Children {
		total += c.Size() // the same call on every child
	}
	return total
}

func (d Folder) Show(indent int) {
	fmt.Printf("%s%s (%d KB)\n", strings.Repeat(" ", indent), d.Name, d.Size())
	for _, c := range d.Children {
		c.Show(indent + 2)
	}
}

func main() {
	root := Folder{"root", []Node{
		File{"photo.jpg", 300},
		File{"notes.txt", 20},
		Folder{"docs", []Node{File{"a.pdf", 100}, File{"b.pdf", 150}}},
	}}
	root.Show(0)
}
Output (identical in all five languages)
root (570 KB)
  photo.jpg (300 KB)
  notes.txt (20 KB)
  docs (250 KB)
    a.pdf (100 KB)
    b.pdf (150 KB)

Use it when

  • Your data is naturally a tree (file system, UI components, menus, org chart, expression trees).
  • You want client code to ignore the difference between one object and a group.

Skip it when

  • The structure is flat. A list is enough.
  • Leaves and containers have very different operations. Forcing one interface makes unsafe methods (File.add()).

Where it shows up in LLD

  • File System / Google Drive design: File and Folder.
  • Menu or category trees in Food Delivery or E-commerce.
  • Comment threads and org charts.

Going deeper SDE-2 and SDE-3

  • Safety versus transparency: should add(child) be on the common interface (transparent, but a File can be asked to add) or only on Folder (safe, but callers must check type)? GoF discuss this trade-off.
  • Recursion is natural here: the container's method calls the same method on its children.
  • Cache computed values (like total size) in containers if the tree is large, and invalidate when a child changes.
  • Composite is often combined with Iterator (walk the tree) and Visitor (do many operations on the tree without adding methods).

Common mistakes

  • Cycles: a folder containing itself loops forever.
  • Over-general interfaces that let nonsense calls through.
Structural

Decorator

Add behaviour to an object by wrapping it, without changing its class and without a subclass for every combination.

Explain it like I am new

Ordering coffee. You start with an espresso, then wrap it with milk, then with mocha. Each add-on changes the price and the description, and you can stack them in any order.

The problem

A coffee can have milk, mocha, whipped cream, extra shot, in any mix. Making a subclass for each combination (EspressoWithMilkAndMocha) leads to dozens of classes, and adding one new topping doubles the count.

The idea

Make each add-on a class that implements the same interface as the coffee and holds another coffee inside. Its cost() calls the inner coffee's cost() and adds its own. Wrap as many layers as you like at runtime.

Decorator class diagram<<interface>>Coffee+description()+cost()Espresso<<abstract>>ToppingDecorator-inner: CoffeeMilkMochawraps
Each topping is a Coffee that contains another Coffee. Stacking them builds the final drink.

See it in code

An espresso is wrapped with milk and then mocha. Each wrapper adds to the description and the price.

Python · main.py

from abc import ABC, abstractmethod


class Coffee(ABC):
    @abstractmethod
    def description(self): ...

    @abstractmethod
    def cost(self): ...


class Espresso(Coffee):
    def description(self): return "Espresso"
    def cost(self): return 50


class ToppingDecorator(Coffee):
    def __init__(self, inner):
        self.inner = inner  # the wrapped coffee


class Milk(ToppingDecorator):
    def description(self): return self.inner.description() + " + Milk"
    def cost(self): return self.inner.cost() + 10


class Mocha(ToppingDecorator):
    def description(self): return self.inner.description() + " + Mocha"
    def cost(self): return self.inner.cost() + 15


drink = Espresso()
print(f"{drink.description()}: Rs {drink.cost()}")
drink = Milk(drink)
print(f"{drink.description()}: Rs {drink.cost()}")
drink = Mocha(drink)
print(f"{drink.description()}: Rs {drink.cost()}")

Java · Main.java

public class Main {
    static void show(Coffee c) { System.out.println(c.description() + ": Rs " + c.cost()); }

    public static void main(String[] args) {
        Coffee drink = new Espresso();
        show(drink);
        drink = new Milk(drink);
        show(drink);
        drink = new Mocha(drink);
        show(drink);
    }
}

interface Coffee {
    String description();
    int cost();
}

class Espresso implements Coffee {
    public String description() { return "Espresso"; }
    public int cost() { return 50; }
}

abstract class ToppingDecorator implements Coffee {
    protected final Coffee inner; // the wrapped coffee
    ToppingDecorator(Coffee inner) { this.inner = inner; }
}

class Milk extends ToppingDecorator {
    Milk(Coffee inner) { super(inner); }
    public String description() { return inner.description() + " + Milk"; }
    public int cost() { return inner.cost() + 10; }
}

class Mocha extends ToppingDecorator {
    Mocha(Coffee inner) { super(inner); }
    public String description() { return inner.description() + " + Mocha"; }
    public int cost() { return inner.cost() + 15; }
}

C++ · main.cpp

#include <iostream>
#include <memory>
#include <string>

struct Coffee {
    virtual ~Coffee() = default;
    virtual std::string description() const = 0;
    virtual int cost() const = 0;
};

struct Espresso : Coffee {
    std::string description() const override { return "Espresso"; }
    int cost() const override { return 50; }
};

struct ToppingDecorator : Coffee {
    explicit ToppingDecorator(std::shared_ptr<Coffee> c) : inner(std::move(c)) {}  // the wrapped coffee
    std::shared_ptr<Coffee> inner;
};

struct Milk : ToppingDecorator {
    using ToppingDecorator::ToppingDecorator;
    std::string description() const override { return inner->description() + " + Milk"; }
    int cost() const override { return inner->cost() + 10; }
};

struct Mocha : ToppingDecorator {
    using ToppingDecorator::ToppingDecorator;
    std::string description() const override { return inner->description() + " + Mocha"; }
    int cost() const override { return inner->cost() + 15; }
};

void show(const std::shared_ptr<Coffee>& c) { std::cout << c->description() << ": Rs " << c->cost() << "\n"; }

int main() {
    std::shared_ptr<Coffee> drink = std::make_shared<Espresso>();
    show(drink);
    drink = std::make_shared<Milk>(drink);
    show(drink);
    drink = std::make_shared<Mocha>(drink);
    show(drink);
}

JavaScript · main.js

class Espresso {
  description() { return "Espresso"; }
  cost() { return 50; }
}

class Milk {
  constructor(inner) { this.inner = inner; } // the wrapped coffee
  description() { return this.inner.description() + " + Milk"; }
  cost() { return this.inner.cost() + 10; }
}

class Mocha {
  constructor(inner) { this.inner = inner; }
  description() { return this.inner.description() + " + Mocha"; }
  cost() { return this.inner.cost() + 15; }
}

const show = (c) => console.log(`${c.description()}: Rs ${c.cost()}`);

let drink = new Espresso();
show(drink);
drink = new Milk(drink);
show(drink);
drink = new Mocha(drink);
show(drink);

Go · main.go

package main

import "fmt"

type Coffee interface {
	Description() string
	Cost() int
}

type Espresso struct{}

func (Espresso) Description() string { return "Espresso" }
func (Espresso) Cost() int           { return 50 }

type Milk struct{ inner Coffee } // the wrapped coffee

func (m Milk) Description() string { return m.inner.Description() + " + Milk" }
func (m Milk) Cost() int           { return m.inner.Cost() + 10 }

type Mocha struct{ inner Coffee }

func (m Mocha) Description() string { return m.inner.Description() + " + Mocha" }
func (m Mocha) Cost() int           { return m.inner.Cost() + 15 }

func show(c Coffee) { fmt.Printf("%s: Rs %d\n", c.Description(), c.Cost()) }

func main() {
	var drink Coffee = Espresso{}
	show(drink)
	drink = Milk{drink}
	show(drink)
	drink = Mocha{drink}
	show(drink)
}
Output (identical in all five languages)
Espresso: Rs 50
Espresso + Milk: Rs 60
Espresso + Milk + Mocha: Rs 75

Use it when

  • You need to add responsibilities to individual objects at runtime.
  • Subclassing would create too many combinations.
  • You want to add features without touching tested code (Open/Closed).

Skip it when

  • There is only one possible extra. A flag or a subclass is simpler.
  • Order of wrapping matters a lot and is hard for callers to get right.

Where it shows up in LLD

  • Pizza, Coffee or Burger pricing with toppings.
  • Stream or text processing: buffering, compression, encryption layered on a base stream (Java I/O is built this way).
  • Notification system: wrap a sender with retry, logging and rate limiting.

Going deeper SDE-2 and SDE-3

  • Decorator and the wrapped object share an interface, so decorators are invisible to callers. Compare with Proxy (same shape, but controls access) and Adapter (changes the interface).
  • Python's @decorator syntax, Java's BufferedReader(new FileReader(...)) and Express/Koa middleware are all this idea.
  • Order matters: Compress(Encrypt(data)) is not the same as Encrypt(Compress(data)) (compress first is far better).
  • A downside is many tiny wrapper objects and stack traces that go through every layer.

Common mistakes

  • Relying on the concrete type of the wrapped object (type checks break once wrapped).
  • Decorators that do too much.
Structural

Facade

Give a complicated group of classes one simple front door.

Explain it like I am new

A hotel concierge. You say 'book me a table and a cab for 8pm'. The concierge deals with the restaurant, the taxi company and the bill. You never learn their phone numbers.

The problem

Placing an order needs inventory, payment and shipping, in the right order, with the right arguments. If every screen or API handler repeats those steps, they all know too much and one change breaks them all.

The idea

Create a Facade class with a small method (placeOrder) that calls the subsystems in the right order. Clients call only the facade. The subsystems stay available if someone needs full control.

Facade class diagramClientOrderFacade+placeOrder(item, price)InventoryPaymentShipping1 call
The client makes one call. The facade knows the order of the subsystem steps.

See it in code

One call, placeOrder, runs inventory, payment and shipping in order.

Python · main.py

class Inventory:
    def reserve(self, item): print(f"Inventory: reserved {item}")


class Payment:
    def charge(self, amount): print(f"Payment: charged {amount}")


class Shipping:
    def schedule(self, item): print(f"Shipping: scheduled {item}")


class OrderFacade:
    def __init__(self):
        self.inventory, self.payment, self.shipping = Inventory(), Payment(), Shipping()

    def place_order(self, item, price):
        self.inventory.reserve(item)
        self.payment.charge(price)
        self.shipping.schedule(item)
        print("Order placed")


OrderFacade().place_order("book", 300)  # one call instead of three

Java · Main.java

public class Main {
    public static void main(String[] args) {
        new OrderFacade().placeOrder("book", 300); // one call instead of three
    }
}

class Inventory { void reserve(String item) { System.out.println("Inventory: reserved " + item); } }
class Payment { void charge(int amount) { System.out.println("Payment: charged " + amount); } }
class Shipping { void schedule(String item) { System.out.println("Shipping: scheduled " + item); } }

class OrderFacade {
    private final Inventory inventory = new Inventory();
    private final Payment payment = new Payment();
    private final Shipping shipping = new Shipping();

    void placeOrder(String item, int price) {
        inventory.reserve(item);
        payment.charge(price);
        shipping.schedule(item);
        System.out.println("Order placed");
    }
}

C++ · main.cpp

#include <iostream>
#include <string>

struct Inventory { void reserve(const std::string& item) { std::cout << "Inventory: reserved " << item << "\n"; } };
struct Payment { void charge(int amount) { std::cout << "Payment: charged " << amount << "\n"; } };
struct Shipping { void schedule(const std::string& item) { std::cout << "Shipping: scheduled " << item << "\n"; } };

class OrderFacade {
public:
    void placeOrder(const std::string& item, int price) {
        inventory_.reserve(item);
        payment_.charge(price);
        shipping_.schedule(item);
        std::cout << "Order placed\n";
    }

private:
    Inventory inventory_;
    Payment payment_;
    Shipping shipping_;
};

int main() {
    OrderFacade().placeOrder("book", 300);  // one call instead of three
}

JavaScript · main.js

class Inventory { reserve(item) { console.log(`Inventory: reserved ${item}`); } }
class Payment { charge(amount) { console.log(`Payment: charged ${amount}`); } }
class Shipping { schedule(item) { console.log(`Shipping: scheduled ${item}`); } }

class OrderFacade {
  constructor() {
    this.inventory = new Inventory();
    this.payment = new Payment();
    this.shipping = new Shipping();
  }
  placeOrder(item, price) {
    this.inventory.reserve(item);
    this.payment.charge(price);
    this.shipping.schedule(item);
    console.log("Order placed");
  }
}

new OrderFacade().placeOrder("book", 300); // one call instead of three

Go · main.go

package main

import "fmt"

type Inventory struct{}
type Payment struct{}
type Shipping struct{}

func (Inventory) Reserve(item string) { fmt.Println("Inventory: reserved", item) }
func (Payment) Charge(amount int)     { fmt.Println("Payment: charged", amount) }
func (Shipping) Schedule(item string) { fmt.Println("Shipping: scheduled", item) }

type OrderFacade struct {
	inventory Inventory
	payment   Payment
	shipping  Shipping
}

func (f OrderFacade) PlaceOrder(item string, price int) {
	f.inventory.Reserve(item)
	f.payment.Charge(price)
	f.shipping.Schedule(item)
	fmt.Println("Order placed")
}

func main() {
	OrderFacade{}.PlaceOrder("book", 300) // one call instead of three
}
Output (identical in all five languages)
Inventory: reserved book
Payment: charged 300
Shipping: scheduled book
Order placed

Use it when

  • A subsystem has many classes and most callers only need a few common tasks.
  • You want to layer a system and limit what depends on what.
  • You are wrapping messy legacy code behind a clean entry point.

Skip it when

  • The facade starts to contain business logic. It should coordinate, not decide.
  • There is only one underlying class. That is just a wrapper.

Where it shows up in LLD

  • Order placement in Food Delivery or E-commerce (inventory + payment + delivery).
  • ATM: a single withdraw that talks to card reader, bank and cash dispenser.
  • Movie ticket booking: seat lock, payment, confirmation.

Going deeper SDE-2 and SDE-3

  • Facade simplifies, Adapter converts, Decorator adds behaviour, Proxy controls access. All four 'wrap' something, so be ready to explain the intent of each.
  • A facade is often a Singleton, and often becomes a 'service' layer in real applications (OrderService).
  • A risk is a God object: the facade grows into a class that does everything. Keep it thin and push logic into the subsystems.
  • Failure handling matters: if payment succeeds but shipping fails, the facade must undo. This leads to sagas and compensation.

Common mistakes

  • Letting the facade become a dumping ground for logic.
  • Hiding the subsystems so completely that power users cannot reach them.
Structural

Flyweight

Save memory by sharing the parts of many objects that are identical, and keeping only the differences separate.

Explain it like I am new

A printing press has one metal block for the letter 'e' and presses it thousands of times. It does not cast a new 'e' for every position on every page.

The problem

A forest game draws a million trees. Each tree stores its name, colour and a heavy texture, plus its own position. Most of that data is the same for every oak, so you waste gigabytes copying it.

The idea

Split each object into shared (intrinsic) data that never changes, such as the tree type with its name, colour and texture, and unique (extrinsic) data such as position. Keep one shared object per type in a small factory and let each tree hold only its position plus a reference to the shared type.

Flyweight class diagramTree-x, -y (unique)-type: TreeTypeTreeType-name, -color (shared)+draw(x, y)TreeTypeFactory-cache: Map+get(name, color)sharescaches
Thousands of Tree objects point to a handful of shared TreeType objects handed out by the factory.

See it in code

Five trees are planted using only two shared tree types.

Python · main.py

class TreeType:  # shared, never changes
    def __init__(self, name, color):
        self.name, self.color = name, color


class TreeTypeFactory:
    _cache = {}

    @classmethod
    def get(cls, name, color):
        key = (name, color)
        if key not in cls._cache:
            cls._cache[key] = TreeType(name, color)  # created once per kind
        return cls._cache[key]


class Tree:  # only the position is unique
    def __init__(self, x, y, tree_type):
        self.x, self.y, self.type = x, y, tree_type

    def describe(self):
        return f"{self.type.name} tree ({self.type.color}) at ({self.x}, {self.y})"


trees = [
    Tree(1, 1, TreeTypeFactory.get("oak", "green")),
    Tree(2, 2, TreeTypeFactory.get("pine", "dark green")),
    Tree(3, 3, TreeTypeFactory.get("oak", "green")),
    Tree(4, 4, TreeTypeFactory.get("oak", "green")),
    Tree(5, 5, TreeTypeFactory.get("pine", "dark green")),
]
print(trees[0].describe())
print(f"planted {len(trees)} trees")
print(f"tree types created: {len(TreeTypeFactory._cache)}")

Java · Main.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        List<Tree> trees = new ArrayList<>();
        trees.add(new Tree(1, 1, TreeTypeFactory.get("oak", "green")));
        trees.add(new Tree(2, 2, TreeTypeFactory.get("pine", "dark green")));
        trees.add(new Tree(3, 3, TreeTypeFactory.get("oak", "green")));
        trees.add(new Tree(4, 4, TreeTypeFactory.get("oak", "green")));
        trees.add(new Tree(5, 5, TreeTypeFactory.get("pine", "dark green")));

        System.out.println(trees.get(0).describe());
        System.out.println("planted " + trees.size() + " trees");
        System.out.println("tree types created: " + TreeTypeFactory.count());
    }
}

class TreeType { // shared, never changes
    final String name, color;
    TreeType(String name, String color) { this.name = name; this.color = color; }
}

class TreeTypeFactory {
    private static final Map<String, TreeType> cache = new HashMap<>();

    static TreeType get(String name, String color) {
        // created once per kind
        return cache.computeIfAbsent(name + "/" + color, k -> new TreeType(name, color));
    }
    static int count() { return cache.size(); }
}

class Tree { // only the position is unique
    private final int x, y;
    private final TreeType type;

    Tree(int x, int y, TreeType type) { this.x = x; this.y = y; this.type = type; }

    String describe() { return type.name + " tree (" + type.color + ") at (" + x + ", " + y + ")"; }
}

C++ · main.cpp

#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>

struct TreeType {  // shared, never changes
    std::string name, color;
};

class TreeTypeFactory {
public:
    static std::shared_ptr<TreeType> get(const std::string& name, const std::string& color) {
        auto key = std::make_pair(name, color);
        auto it = cache().find(key);
        if (it == cache().end())
            it = cache().emplace(key, std::make_shared<TreeType>(TreeType{name, color})).first;  // once per kind
        return it->second;
    }
    static size_t count() { return cache().size(); }

private:
    static std::map<std::pair<std::string, std::string>, std::shared_ptr<TreeType>>& cache() {
        static std::map<std::pair<std::string, std::string>, std::shared_ptr<TreeType>> c;
        return c;
    }
};

struct Tree {  // only the position is unique
    int x, y;
    std::shared_ptr<TreeType> type;
    std::string describe() const {
        return type->name + " tree (" + type->color + ") at (" + std::to_string(x) + ", " + std::to_string(y) + ")";
    }
};

int main() {
    std::vector<Tree> trees = {
        {1, 1, TreeTypeFactory::get("oak", "green")},
        {2, 2, TreeTypeFactory::get("pine", "dark green")},
        {3, 3, TreeTypeFactory::get("oak", "green")},
        {4, 4, TreeTypeFactory::get("oak", "green")},
        {5, 5, TreeTypeFactory::get("pine", "dark green")},
    };
    std::cout << trees[0].describe() << "\n";
    std::cout << "planted " << trees.size() << " trees\n";
    std::cout << "tree types created: " << TreeTypeFactory::count() << "\n";
}

JavaScript · main.js

class TreeType { // shared, never changes
  constructor(name, color) { this.name = name; this.color = color; }
}

class TreeTypeFactory {
  static #cache = new Map();
  static get(name, color) {
    const key = `${name}/${color}`;
    if (!TreeTypeFactory.#cache.has(key)) TreeTypeFactory.#cache.set(key, new TreeType(name, color)); // once per kind
    return TreeTypeFactory.#cache.get(key);
  }
  static count() { return TreeTypeFactory.#cache.size; }
}

class Tree { // only the position is unique
  constructor(x, y, type) { this.x = x; this.y = y; this.type = type; }
  describe() { return `${this.type.name} tree (${this.type.color}) at (${this.x}, ${this.y})`; }
}

const trees = [
  new Tree(1, 1, TreeTypeFactory.get("oak", "green")),
  new Tree(2, 2, TreeTypeFactory.get("pine", "dark green")),
  new Tree(3, 3, TreeTypeFactory.get("oak", "green")),
  new Tree(4, 4, TreeTypeFactory.get("oak", "green")),
  new Tree(5, 5, TreeTypeFactory.get("pine", "dark green")),
];
console.log(trees[0].describe());
console.log(`planted ${trees.length} trees`);
console.log(`tree types created: ${TreeTypeFactory.count()}`);

Go · main.go

package main

import "fmt"

type TreeType struct{ Name, Color string } // shared, never changes

var cache = map[string]*TreeType{}

func GetTreeType(name, color string) *TreeType {
	key := name + "/" + color
	if _, ok := cache[key]; !ok {
		cache[key] = &TreeType{name, color} // created once per kind
	}
	return cache[key]
}

type Tree struct { // only the position is unique
	X, Y int
	Type *TreeType
}

func (t Tree) Describe() string {
	return fmt.Sprintf("%s tree (%s) at (%d, %d)", t.Type.Name, t.Type.Color, t.X, t.Y)
}

func main() {
	trees := []Tree{
		{1, 1, GetTreeType("oak", "green")},
		{2, 2, GetTreeType("pine", "dark green")},
		{3, 3, GetTreeType("oak", "green")},
		{4, 4, GetTreeType("oak", "green")},
		{5, 5, GetTreeType("pine", "dark green")},
	}
	fmt.Println(trees[0].Describe())
	fmt.Printf("planted %d trees\n", len(trees))
	fmt.Printf("tree types created: %d\n", len(cache))
}
Output (identical in all five languages)
oak tree (green) at (1, 1)
planted 5 trees
tree types created: 2

Use it when

  • You create a huge number of similar objects and memory is the bottleneck.
  • Much of each object's state is identical across many objects.
  • The shared part can be immutable.

Skip it when

  • You have few objects. The extra factory and indirection add complexity for no gain.
  • Objects are mostly unique.

Where it shows up in LLD

  • Text editor: one shared glyph per character, many positions.
  • Chess or board games: shared piece types, many positions (or the game of many identical enemies).
  • Parking Lot: shared VehicleType or SpotType objects.

Going deeper SDE-2 and SDE-3

  • The shared part must be immutable, or one change would show up in every object that shares it.
  • The factory is usually a cache (a map from key to flyweight), so it often looks like a Singleton or a Pool. The difference from Object Pool is that flyweights are shared at the same time, pool objects are borrowed by one user at a time.
  • Real examples: Java Integer.valueOf caching small integers, string interning, icon caches.
  • The trade-off is CPU for memory: you pass the extrinsic state into method calls and look up shared objects.

Common mistakes

  • Putting mutable state in the shared object.
  • Creating a new 'shared' object every time because the cache key was wrong.
Structural

Proxy

Put a stand-in object in front of another one to control access to it: delay it, guard it, cache it or log it.

Explain it like I am new

A company's receptionist. You ask for the manager, but the receptionist decides if you have an appointment, tells you to wait, and only then lets you in. To you it still feels like talking to the company.

The problem

Creating or calling an object can be slow (loading a huge image), restricted (only admins can call it), remote (a service on another machine) or something you want to count or cache. You do not want every caller to handle that.

The idea

Create a Proxy that implements the same interface as the real object and holds a reference to it. The proxy decides when and whether to forward each call. Callers cannot tell the difference.

Proxy class diagramClient<<interface>>Image+display()ImageProxy-real: RealImageRealImage(slow to load)creates on demand
The proxy and the real image share an interface. The proxy creates the real one only when needed.

See it in code

A big image is only loaded from disk the first time it is displayed. The second display reuses it.

Python · main.py

class RealImage:
    def __init__(self, name):
        self.name = name
        print(f"Loading {name} from disk")  # slow work happens here

    def display(self):
        print(f"Displaying {self.name}")


class ImageProxy:
    def __init__(self, name):
        self.name, self._real = name, None
        print("proxy created (nothing loaded yet)")

    def display(self):
        if self._real is None:  # load only on first use
            self._real = RealImage(self.name)
        self._real.display()


image = ImageProxy("big.png")
image.display()
image.display()

Java · Main.java

public class Main {
    public static void main(String[] args) {
        Image image = new ImageProxy("big.png");
        image.display();
        image.display();
    }
}

interface Image { void display(); }

class RealImage implements Image {
    private final String name;
    RealImage(String name) {
        this.name = name;
        System.out.println("Loading " + name + " from disk"); // slow work happens here
    }
    public void display() { System.out.println("Displaying " + name); }
}

class ImageProxy implements Image {
    private final String name;
    private RealImage real;

    ImageProxy(String name) {
        this.name = name;
        System.out.println("proxy created (nothing loaded yet)");
    }

    public void display() {
        if (real == null) real = new RealImage(name); // load only on first use
        real.display();
    }
}

C++ · main.cpp

#include <iostream>
#include <memory>
#include <string>

struct Image {
    virtual ~Image() = default;
    virtual void display() = 0;
};

class RealImage : public Image {
public:
    explicit RealImage(std::string name) : name_(std::move(name)) {
        std::cout << "Loading " << name_ << " from disk\n";  // slow work happens here
    }
    void display() override { std::cout << "Displaying " << name_ << "\n"; }

private:
    std::string name_;
};

class ImageProxy : public Image {
public:
    explicit ImageProxy(std::string name) : name_(std::move(name)) {
        std::cout << "proxy created (nothing loaded yet)\n";
    }
    void display() override {
        if (!real_) real_ = std::make_unique<RealImage>(name_);  // load only on first use
        real_->display();
    }

private:
    std::string name_;
    std::unique_ptr<RealImage> real_;
};

int main() {
    ImageProxy image("big.png");
    image.display();
    image.display();
}

JavaScript · main.js

class RealImage {
  constructor(name) {
    this.name = name;
    console.log(`Loading ${name} from disk`); // slow work happens here
  }
  display() { console.log(`Displaying ${this.name}`); }
}

class ImageProxy {
  constructor(name) {
    this.name = name;
    this.real = null;
    console.log("proxy created (nothing loaded yet)");
  }
  display() {
    if (this.real === null) this.real = new RealImage(this.name); // load only on first use
    this.real.display();
  }
}

const image = new ImageProxy("big.png");
image.display();
image.display();

Go · main.go

package main

import "fmt"

type Image interface{ Display() }

type RealImage struct{ name string }

func NewRealImage(name string) *RealImage {
	fmt.Printf("Loading %s from disk\n", name) // slow work happens here
	return &RealImage{name}
}

func (r *RealImage) Display() { fmt.Printf("Displaying %s\n", r.name) }

type ImageProxy struct {
	name string
	real *RealImage
}

func NewImageProxy(name string) *ImageProxy {
	fmt.Println("proxy created (nothing loaded yet)")
	return &ImageProxy{name: name}
}

func (p *ImageProxy) Display() {
	if p.real == nil { // load only on first use
		p.real = NewRealImage(p.name)
	}
	p.real.Display()
}

func main() {
	var image Image = NewImageProxy("big.png")
	image.Display()
	image.Display()
}
Output (identical in all five languages)
proxy created (nothing loaded yet)
Loading big.png from disk
Displaying big.png
Displaying big.png

Use it when

  • Lazy loading: create the expensive object only when first used (virtual proxy).
  • Access control: check permissions before forwarding (protection proxy).
  • Remote objects: hide the network call (remote proxy, as in RPC and gRPC stubs).
  • Caching, logging or rate limiting in front of a service (smart proxy).

Skip it when

  • You only need to add features to the object itself. That is a Decorator.
  • A plain function call with a simple check is enough.

Where it shows up in LLD

  • Image or video loading in a media app.
  • Rate limiter or cache in front of a service.
  • Access control for admin-only operations in Library or Banking systems.

Going deeper SDE-2 and SDE-3

  • Proxy and Decorator have the same structure. The difference is intent: Decorator adds behaviour the caller asked for, Proxy controls access and usually manages the lifecycle of the real object.
  • Frameworks use proxies heavily: Spring AOP, Hibernate lazy loading, Python unittest.mock, JS Proxy.
  • A caching proxy needs an invalidation strategy or it serves stale data forever.
  • Thread safety: lazy creation inside a proxy has the same race condition as a lazy Singleton.

Common mistakes

  • Proxy that changes behaviour in surprising ways (callers expect the real thing).
  • Hidden cost: a network call that looks like a local method call.

Behavioral patterns

These eleven patterns are about communication and responsibility: who does what, who gets told, and how an algorithm or request moves between objects.

Behavioral

Chain of Responsibility

Pass a request along a line of handlers until one of them deals with it.

Explain it like I am new

An expense claim. Your manager approves small amounts. Bigger ones go up to a director, and the largest to a VP. You just hand in the claim, you do not need to know who will approve it.

The problem

A request can be handled by different objects depending on its size or type, and the sender should not need a long if amount < 1000 ... else if amount < 5000 ... chain that knows every handler.

The idea

Give every handler the same interface and a reference to the next handler. Each one either handles the request or passes it on. The sender only talks to the first handler, and you can add, remove or reorder handlers without touching the sender.

Chain of Responsibility class diagramClientManagerlimit 1,000Directorlimit 5,000VPno limitnextnext
Each handler either approves the claim or passes it to the next one.

See it in code

Three approvers form a chain. Each claim is approved by the first person whose limit is high enough.

Python · main.py

class Approver:
    def __init__(self, name, limit, next_approver=None):
        self.name, self.limit, self.next = name, limit, next_approver

    def handle(self, amount):
        if amount <= self.limit:
            print(f"{self.name} approved {amount}")
        elif self.next:
            self.next.handle(amount)  # pass it up the chain
        else:
            print("nobody can approve", amount)


NO_LIMIT = 10**9
chain = Approver("Manager", 1000, Approver("Director", 5000, Approver("VP", NO_LIMIT)))

for amount in (500, 3000, 20000):
    chain.handle(amount)

Java · Main.java

public class Main {
    public static void main(String[] args) {
        int noLimit = 1_000_000_000;
        Approver chain = new Approver("Manager", 1000, new Approver("Director", 5000, new Approver("VP", noLimit, null)));

        for (int amount : new int[]{500, 3000, 20000}) chain.handle(amount);
    }
}

class Approver {
    private final String name;
    private final int limit;
    private final Approver next;

    Approver(String name, int limit, Approver next) { this.name = name; this.limit = limit; this.next = next; }

    void handle(int amount) {
        if (amount <= limit) System.out.println(name + " approved " + amount);
        else if (next != null) next.handle(amount); // pass it up the chain
        else System.out.println("nobody can approve " + amount);
    }
}

C++ · main.cpp

#include <iostream>
#include <memory>
#include <string>

class Approver {
public:
    Approver(std::string name, int limit, std::unique_ptr<Approver> next = nullptr)
        : name_(std::move(name)), limit_(limit), next_(std::move(next)) {}

    void handle(int amount) const {
        if (amount <= limit_) std::cout << name_ << " approved " << amount << "\n";
        else if (next_) next_->handle(amount);  // pass it up the chain
        else std::cout << "nobody can approve " << amount << "\n";
    }

private:
    std::string name_;
    int limit_;
    std::unique_ptr<Approver> next_;
};

int main() {
    const int noLimit = 1000000000;
    Approver chain("Manager", 1000,
        std::make_unique<Approver>("Director", 5000,
            std::make_unique<Approver>("VP", noLimit)));

    for (int amount : {500, 3000, 20000}) chain.handle(amount);
}

JavaScript · main.js

class Approver {
  constructor(name, limit, next = null) { this.name = name; this.limit = limit; this.next = next; }

  handle(amount) {
    if (amount <= this.limit) console.log(`${this.name} approved ${amount}`);
    else if (this.next) this.next.handle(amount); // pass it up the chain
    else console.log("nobody can approve", amount);
  }
}

const NO_LIMIT = 1e9;
const chain = new Approver("Manager", 1000, new Approver("Director", 5000, new Approver("VP", NO_LIMIT)));

for (const amount of [500, 3000, 20000]) chain.handle(amount);

Go · main.go

package main

import "fmt"

type Approver struct {
	name  string
	limit int
	next  *Approver
}

func (a *Approver) Handle(amount int) {
	switch {
	case amount <= a.limit:
		fmt.Printf("%s approved %d\n", a.name, amount)
	case a.next != nil:
		a.next.Handle(amount) // pass it up the chain
	default:
		fmt.Println("nobody can approve", amount)
	}
}

func main() {
	const noLimit = 1_000_000_000
	chain := &Approver{"Manager", 1000, &Approver{"Director", 5000, &Approver{"VP", noLimit, nil}}}

	for _, amount := range []int{500, 3000, 20000} {
		chain.Handle(amount)
	}
}
Output (identical in all five languages)
Manager approved 500
Director approved 3000
VP approved 20000

Use it when

  • More than one object may handle a request and the right one is not known in advance.
  • You want to decouple the sender from the receivers.
  • Handlers should be configurable at runtime (middleware, validation steps, approval levels).

Skip it when

  • Exactly one object always handles the request. Call it directly.
  • A request must be handled by every step with no early exit. That is a pipeline, not a chain.

Where it shows up in LLD

  • ATM cash dispenser: Rs 2000 notes handler, then Rs 500, then Rs 100.
  • Logger levels (debug, info, error) and support ticket escalation.
  • Vending machine or approval workflows, request validation, middleware.

Going deeper SDE-2 and SDE-3

  • A chain can stop at the first handler that succeeds (classic) or let every handler act (like middleware). Decide and document which one you mean.
  • A request that nobody handles needs a defined outcome: an error, a default handler at the end, or silent drop.
  • Express/Koa middleware, Java servlet filters and Spring Security filters are all chains of responsibility.
  • Chain versus Decorator: both wrap and delegate. A decorator always forwards and adds behaviour, a chain handler may stop the request.

Common mistakes

  • A request falling off the end with no handler.
  • Cycles in the chain.
  • Hard-to-debug order dependencies.
Behavioral

Command

Turn an action into an object, so you can store it, queue it, log it or undo it.

Explain it like I am new

A restaurant order slip. The waiter writes down what you want instead of shouting it at the chef. The slip can wait in a queue, be handed to any chef, be tracked, and even be cancelled.

The problem

A button, a menu item and a keyboard shortcut should all trigger 'turn on the light', and you want undo. If each of them calls light.on() directly, none of them can be reused, queued or undone.

The idea

Wrap each request in an object with an execute() method (and undo() if needed). The object stores everything it needs: the receiver and its arguments. An invoker just calls execute() and can keep a history of the commands it ran.

Command class diagramRemote-history: Stack+press(cmd)+undo()<<interface>>Command+execute()+undo()TurnOnTurnOffLight+set(on)runs
The remote only knows the Command interface. Each command knows its receiver and how to undo itself.

See it in code

A remote presses TurnOn and TurnOff commands, then undoes them one by one in reverse order.

Python · main.py

class Light:
    def __init__(self):
        self.on = False

    def status(self):
        return "light is " + ("on" if self.on else "off")


class TurnOn:
    def __init__(self, light): self.light = light
    def execute(self): self.light.on = True
    def undo(self): self.light.on = False


class TurnOff:
    def __init__(self, light): self.light = light
    def execute(self): self.light.on = False
    def undo(self): self.light.on = True


class Remote:
    def __init__(self):
        self.history = []

    def press(self, command):
        command.execute()
        self.history.append(command)  # remember it so we can undo

    def undo(self):
        self.history.pop().undo()


light, remote = Light(), Remote()
remote.press(TurnOn(light));  print(light.status())
remote.press(TurnOff(light)); print(light.status())
remote.undo(); print("undo ->", light.status())
remote.undo(); print("undo ->", light.status())

Java · Main.java

import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    public static void main(String[] args) {
        Light light = new Light();
        Remote remote = new Remote();
        remote.press(new TurnOn(light));  System.out.println(light.status());
        remote.press(new TurnOff(light)); System.out.println(light.status());
        remote.undo(); System.out.println("undo -> " + light.status());
        remote.undo(); System.out.println("undo -> " + light.status());
    }
}

class Light {
    boolean on = false;
    String status() { return "light is " + (on ? "on" : "off"); }
}

interface Command { void execute(); void undo(); }

class TurnOn implements Command {
    private final Light light;
    TurnOn(Light light) { this.light = light; }
    public void execute() { light.on = true; }
    public void undo() { light.on = false; }
}

class TurnOff implements Command {
    private final Light light;
    TurnOff(Light light) { this.light = light; }
    public void execute() { light.on = false; }
    public void undo() { light.on = true; }
}

class Remote {
    private final Deque<Command> history = new ArrayDeque<>();

    void press(Command c) { c.execute(); history.push(c); } // remember it so we can undo
    void undo() { history.pop().undo(); }
}

C++ · main.cpp

#include <iostream>
#include <memory>
#include <stack>
#include <string>

struct Light {
    bool on = false;
    std::string status() const { return std::string("light is ") + (on ? "on" : "off"); }
};

struct Command {
    virtual ~Command() = default;
    virtual void execute() = 0;
    virtual void undo() = 0;
};

struct TurnOn : Command {
    explicit TurnOn(Light& l) : light(l) {}
    void execute() override { light.on = true; }
    void undo() override { light.on = false; }
    Light& light;
};

struct TurnOff : Command {
    explicit TurnOff(Light& l) : light(l) {}
    void execute() override { light.on = false; }
    void undo() override { light.on = true; }
    Light& light;
};

class Remote {
public:
    void press(std::unique_ptr<Command> c) {
        c->execute();
        history_.push(std::move(c));  // remember it so we can undo
    }
    void undo() {
        history_.top()->undo();
        history_.pop();
    }

private:
    std::stack<std::unique_ptr<Command>> history_;
};

int main() {
    Light light;
    Remote remote;
    remote.press(std::make_unique<TurnOn>(light));  std::cout << light.status() << "\n";
    remote.press(std::make_unique<TurnOff>(light)); std::cout << light.status() << "\n";
    remote.undo(); std::cout << "undo -> " << light.status() << "\n";
    remote.undo(); std::cout << "undo -> " << light.status() << "\n";
}

JavaScript · main.js

class Light {
  on = false;
  status() { return "light is " + (this.on ? "on" : "off"); }
}

class TurnOn {
  constructor(light) { this.light = light; }
  execute() { this.light.on = true; }
  undo() { this.light.on = false; }
}

class TurnOff {
  constructor(light) { this.light = light; }
  execute() { this.light.on = false; }
  undo() { this.light.on = true; }
}

class Remote {
  history = [];
  press(command) { command.execute(); this.history.push(command); } // remember it so we can undo
  undo() { this.history.pop().undo(); }
}

const light = new Light();
const remote = new Remote();
remote.press(new TurnOn(light));  console.log(light.status());
remote.press(new TurnOff(light)); console.log(light.status());
remote.undo(); console.log("undo ->", light.status());
remote.undo(); console.log("undo ->", light.status());

Go · main.go

package main

import "fmt"

type Light struct{ on bool }

func (l *Light) Status() string {
	if l.on {
		return "light is on"
	}
	return "light is off"
}

type Command interface {
	Execute()
	Undo()
}

type TurnOn struct{ light *Light }
type TurnOff struct{ light *Light }

func (c TurnOn) Execute()  { c.light.on = true }
func (c TurnOn) Undo()     { c.light.on = false }
func (c TurnOff) Execute() { c.light.on = false }
func (c TurnOff) Undo()    { c.light.on = true }

type Remote struct{ history []Command }

func (r *Remote) Press(c Command) {
	c.Execute()
	r.history = append(r.history, c) // remember it so we can undo
}

func (r *Remote) Undo() {
	last := r.history[len(r.history)-1]
	r.history = r.history[:len(r.history)-1]
	last.Undo()
}

func main() {
	light, remote := &Light{}, &Remote{}
	remote.Press(TurnOn{light})
	fmt.Println(light.Status())
	remote.Press(TurnOff{light})
	fmt.Println(light.Status())
	remote.Undo()
	fmt.Println("undo ->", light.Status())
	remote.Undo()
	fmt.Println("undo ->", light.Status())
}
Output (identical in all five languages)
light is on
light is off
undo -> light is on
undo -> light is off

Use it when

  • You need undo/redo.
  • You want to queue, schedule, retry or log operations.
  • You want to decouple whoever triggers an action (a button) from whoever performs it (a light).

Skip it when

  • A simple function call is enough.
  • No history, queue or undo is required. A command object is overhead.

Where it shows up in LLD

  • Text editor with undo/redo.
  • Smart Home remote control.
  • Job scheduler and task queue (each task is a command).
  • Chess move history.

Going deeper SDE-2 and SDE-3

  • Undo can be done two ways: store the previous state (a memento) inside the command, or compute the inverse operation. Inverse is lighter but not always possible (deleting a file).
  • Macro commands combine several commands into one: a Composite of Commands.
  • In functional languages a command is just a closure. The class form earns its keep when you need undo, serialization or metadata.
  • Event sourcing and database write-ahead logs are Command at architecture scale: store the commands, replay them to rebuild state.

Common mistakes

  • Commands that keep references to objects that no longer exist.
  • Unbounded history growing forever.
Behavioral

Interpreter

Represent the rules of a tiny language as classes, so you can evaluate sentences written in it.

Explain it like I am new

Reading sheet music. Each symbol means something, and the player combines them following the rules. Nobody asks the page to play itself, the interpreter reads it and acts.

The problem

You need to evaluate small expressions that arrive as text: a filter like age > 18 AND country = IN, a math formula, a search query. Hard-coding each possibility does not scale.

The idea

Define a class for each grammar rule (Number, Add, Subtract). Each class has an interpret() method. Parse the text into a tree of those objects, then call interpret() on the root. The tree evaluates itself, from the leaves up.

Interpreter class diagram<<interface>>Expression+interpret(): intNumber-valueAdd-left, -rightSubtract-left, -righttwo sub-expressions
Every grammar rule is a class. Add and Subtract hold two sub-expressions, Number is a leaf.

See it in code

A tiny calculator reads expressions like '5 3 + 2 -', builds an expression tree and evaluates it.

Python · main.py

class Number:
    def __init__(self, value): self.value = value
    def interpret(self): return self.value


class Add:
    def __init__(self, left, right): self.left, self.right = left, right
    def interpret(self): return self.left.interpret() + self.right.interpret()


class Subtract:
    def __init__(self, left, right): self.left, self.right = left, right
    def interpret(self): return self.left.interpret() - self.right.interpret()


def parse(text):  # reverse Polish notation: operands first, operator after
    stack = []
    for token in text.split():
        if token == "+":
            right, left = stack.pop(), stack.pop()
            stack.append(Add(left, right))
        elif token == "-":
            right, left = stack.pop(), stack.pop()
            stack.append(Subtract(left, right))
        else:
            stack.append(Number(int(token)))
    return stack.pop()


for text in ("5 3 + 2 -", "10 4 - 3 +"):
    print(f"{text} = {parse(text).interpret()}")

Java · Main.java

import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    static Expression parse(String text) { // reverse Polish notation: operands first, operator after
        Deque<Expression> stack = new ArrayDeque<>();
        for (String token : text.split(" ")) {
            if (token.equals("+")) { Expression r = stack.pop(), l = stack.pop(); stack.push(new Add(l, r)); }
            else if (token.equals("-")) { Expression r = stack.pop(), l = stack.pop(); stack.push(new Subtract(l, r)); }
            else stack.push(new Number(Integer.parseInt(token)));
        }
        return stack.pop();
    }

    public static void main(String[] args) {
        for (String text : new String[]{"5 3 + 2 -", "10 4 - 3 +"})
            System.out.println(text + " = " + parse(text).interpret());
    }
}

interface Expression { int interpret(); }

class Number implements Expression {
    private final int value;
    Number(int value) { this.value = value; }
    public int interpret() { return value; }
}

class Add implements Expression {
    private final Expression left, right;
    Add(Expression l, Expression r) { left = l; right = r; }
    public int interpret() { return left.interpret() + right.interpret(); }
}

class Subtract implements Expression {
    private final Expression left, right;
    Subtract(Expression l, Expression r) { left = l; right = r; }
    public int interpret() { return left.interpret() - right.interpret(); }
}

C++ · main.cpp

#include <iostream>
#include <memory>
#include <sstream>
#include <stack>
#include <string>

struct Expression {
    virtual ~Expression() = default;
    virtual int interpret() const = 0;
};
using Expr = std::shared_ptr<Expression>;

struct Number : Expression {
    int value;
    explicit Number(int v) : value(v) {}
    int interpret() const override { return value; }
};
struct Add : Expression {
    Expr left, right;
    Add(Expr l, Expr r) : left(l), right(r) {}
    int interpret() const override { return left->interpret() + right->interpret(); }
};
struct Subtract : Expression {
    Expr left, right;
    Subtract(Expr l, Expr r) : left(l), right(r) {}
    int interpret() const override { return left->interpret() - right->interpret(); }
};

Expr parse(const std::string& text) {  // reverse Polish notation: operands first, operator after
    std::stack<Expr> st;
    std::istringstream in(text);
    std::string token;
    while (in >> token) {
        if (token == "+" || token == "-") {
            Expr right = st.top(); st.pop();
            Expr left = st.top(); st.pop();
            if (token == "+") st.push(std::make_shared<Add>(left, right));
            else st.push(std::make_shared<Subtract>(left, right));
        } else {
            st.push(std::make_shared<Number>(std::stoi(token)));
        }
    }
    return st.top();
}

int main() {
    for (std::string text : {"5 3 + 2 -", "10 4 - 3 +"})
        std::cout << text << " = " << parse(text)->interpret() << "\n";
}

JavaScript · main.js

class Num { constructor(v) { this.value = v; } interpret() { return this.value; } }
class Add { constructor(l, r) { this.left = l; this.right = r; } interpret() { return this.left.interpret() + this.right.interpret(); } }
class Subtract { constructor(l, r) { this.left = l; this.right = r; } interpret() { return this.left.interpret() - this.right.interpret(); } }

function parse(text) { // reverse Polish notation: operands first, operator after
  const stack = [];
  for (const token of text.split(" ")) {
    if (token === "+") { const r = stack.pop(), l = stack.pop(); stack.push(new Add(l, r)); }
    else if (token === "-") { const r = stack.pop(), l = stack.pop(); stack.push(new Subtract(l, r)); }
    else stack.push(new Num(Number(token)));
  }
  return stack.pop();
}

for (const text of ["5 3 + 2 -", "10 4 - 3 +"]) {
  console.log(`${text} = ${parse(text).interpret()}`);
}

Go · main.go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

type Expression interface{ Interpret() int }

type Number struct{ value int }
type Add struct{ left, right Expression }
type Subtract struct{ left, right Expression }

func (n Number) Interpret() int   { return n.value }
func (a Add) Interpret() int      { return a.left.Interpret() + a.right.Interpret() }
func (s Subtract) Interpret() int { return s.left.Interpret() - s.right.Interpret() }

func parse(text string) Expression { // reverse Polish notation: operands first, operator after
	var stack []Expression
	for _, token := range strings.Fields(text) {
		switch token {
		case "+", "-":
			right, left := stack[len(stack)-1], stack[len(stack)-2]
			stack = stack[:len(stack)-2]
			if token == "+" {
				stack = append(stack, Add{left, right})
			} else {
				stack = append(stack, Subtract{left, right})
			}
		default:
			n, _ := strconv.Atoi(token)
			stack = append(stack, Number{n})
		}
	}
	return stack[0]
}

func main() {
	for _, text := range []string{"5 3 + 2 -", "10 4 - 3 +"} {
		fmt.Printf("%s = %d\n", text, parse(text).Interpret())
	}
}
Output (identical in all five languages)
5 3 + 2 - = 6
10 4 - 3 + = 9

Use it when

  • You have a small, stable grammar (rule engines, search filters, simple formulas, config rules).
  • You can model sentences as a tree.

Skip it when

  • The grammar is large or changes often. Use a parser generator (ANTLR) or an existing library.
  • Performance matters. Walking a tree of objects is slow.

Where it shows up in LLD

  • Rule engine for a coupon or discount system.
  • Search filter or query builder.
  • A calculator or spreadsheet formula.

Going deeper SDE-2 and SDE-3

  • The structure is exactly Composite: terminal expressions are leaves, non-terminal ones are composites. Interpret is the operation.
  • Parsing (text to tree) is separate from interpreting (tree to value). The example uses reverse Polish notation because it parses without any precedence rules.
  • To add operations beyond evaluating (printing, optimizing, type-checking), use Visitor on the tree instead of piling methods on each class.
  • This is the least-used GoF pattern in everyday code. In interviews it appears as 'design a rule engine' or 'design a calculator'.

Common mistakes

  • Using it for a big language.
  • Mixing parsing and evaluation in the same class.
Behavioral

Iterator

Walk through a collection one item at a time without knowing how it stores its items.

Explain it like I am new

A TV remote's 'next channel' button. You do not need to know how the channels are stored or numbered. You press next until you are done, or switch to 'previous' to go the other way.

The problem

A collection can be an array, a linked list, a tree or a database cursor. If callers loop over its internals, they break when the storage changes, and you cannot offer a second way to walk it (forward, reverse, skip some).

The idea

Give the collection a way to hand out a separate iterator object. The iterator has hasNext() and next() and remembers its own position. Callers use only those two methods. Different iterators can walk the same collection in different orders at the same time.

Iterator class diagramPlaylist-songs: List+forward()+reverse()<<interface>>Iterator+hasNext(): bool+next(): SongForwardIteratorReverseIteratorcreates
The playlist hands out iterators. Callers use only hasNext() and next().

See it in code

A playlist can be walked forward or in reverse, each by its own iterator.

Python · main.py

class ReverseIterator:
    def __init__(self, songs):
        self.songs, self.index = songs, len(songs) - 1

    def __iter__(self):
        return self

    def __next__(self):
        if self.index < 0:
            raise StopIteration
        song = self.songs[self.index]
        self.index -= 1
        return song


class Playlist:
    def __init__(self, songs):
        self._songs = songs

    def __iter__(self):  # forward: Python's for-loop calls this
        return iter(self._songs)

    def reverse(self):
        return ReverseIterator(self._songs)


playlist = Playlist(["song1", "song2", "song3"])
print("forward:", " ".join(playlist))
print("reverse:", " ".join(playlist.reverse()))

Java · Main.java

import java.util.Iterator;
import java.util.List;

public class Main {
    static String join(Iterator<String> it) {
        StringBuilder sb = new StringBuilder();
        while (it.hasNext()) sb.append(sb.length() == 0 ? "" : " ").append(it.next());
        return sb.toString();
    }

    public static void main(String[] args) {
        Playlist playlist = new Playlist(List.of("song1", "song2", "song3"));
        System.out.println("forward: " + join(playlist.iterator()));
        System.out.println("reverse: " + join(playlist.reverse()));
    }
}

class Playlist implements Iterable<String> {
    private final List<String> songs;
    Playlist(List<String> songs) { this.songs = songs; }

    public Iterator<String> iterator() { return songs.iterator(); } // forward

    Iterator<String> reverse() {
        return new Iterator<>() {
            private int index = songs.size() - 1;
            public boolean hasNext() { return index >= 0; }
            public String next() { return songs.get(index--); }
        };
    }
}

C++ · main.cpp

#include <iostream>
#include <string>
#include <vector>

class Playlist {
public:
    explicit Playlist(std::vector<std::string> songs) : songs_(std::move(songs)) {}

    class Iterator {  // a small object that remembers its own position
    public:
        Iterator(const std::vector<std::string>& s, bool reverse)
            : songs_(s), reverse_(reverse), index_(reverse ? static_cast<int>(s.size()) - 1 : 0) {}
        bool hasNext() const { return index_ >= 0 && index_ < static_cast<int>(songs_.size()); }
        const std::string& next() { const std::string& s = songs_[index_]; index_ += reverse_ ? -1 : 1; return s; }

    private:
        const std::vector<std::string>& songs_;
        bool reverse_;
        int index_;
    };

    Iterator forward() const { return Iterator(songs_, false); }
    Iterator reverse() const { return Iterator(songs_, true); }

private:
    std::vector<std::string> songs_;
};

std::string join(Playlist::Iterator it) {
    std::string out;
    while (it.hasNext()) out += (out.empty() ? "" : " ") + it.next();
    return out;
}

int main() {
    Playlist playlist({"song1", "song2", "song3"});
    std::cout << "forward: " << join(playlist.forward()) << "\n";
    std::cout << "reverse: " << join(playlist.reverse()) << "\n";
}

JavaScript · main.js

class Playlist {
  constructor(songs) { this.songs = songs; }

  [Symbol.iterator]() { // forward: for...of calls this
    let i = 0;
    const songs = this.songs;
    return { next: () => (i < songs.length ? { value: songs[i++], done: false } : { value: undefined, done: true }) };
  }

  reverse() {
    let i = this.songs.length - 1;
    const songs = this.songs;
    return { next: () => (i >= 0 ? { value: songs[i--], done: false } : { value: undefined, done: true }),
             [Symbol.iterator]() { return this; } };
  }
}

const playlist = new Playlist(["song1", "song2", "song3"]);
console.log("forward:", [...playlist].join(" "));
console.log("reverse:", [...playlist.reverse()].join(" "));

Go · main.go

package main

import (
	"fmt"
	"strings"
)

type Iterator interface {
	Next() (string, bool) // the bool is false when there is nothing left
}

type Playlist struct{ songs []string }

type forwardIter struct {
	songs []string
	i     int
}
type reverseIter struct {
	songs []string
	i     int
}

func (it *forwardIter) Next() (string, bool) {
	if it.i >= len(it.songs) {
		return "", false
	}
	it.i++
	return it.songs[it.i-1], true
}

func (it *reverseIter) Next() (string, bool) {
	if it.i < 0 {
		return "", false
	}
	it.i--
	return it.songs[it.i+1], true
}

func (p Playlist) Forward() Iterator { return &forwardIter{p.songs, 0} }
func (p Playlist) Reverse() Iterator { return &reverseIter{p.songs, len(p.songs) - 1} }

func join(it Iterator) string {
	var parts []string
	for s, ok := it.Next(); ok; s, ok = it.Next() {
		parts = append(parts, s)
	}
	return strings.Join(parts, " ")
}

func main() {
	playlist := Playlist{[]string{"song1", "song2", "song3"}}
	fmt.Println("forward:", join(playlist.Forward()))
	fmt.Println("reverse:", join(playlist.Reverse()))
}
Output (identical in all five languages)
forward: song1 song2 song3
reverse: song3 song2 song1

Use it when

  • You want to hide how a collection is stored.
  • You need more than one way to walk the same data (forward, reverse, filtered).
  • You want a uniform way to loop over different collections.

Skip it when

  • A plain for loop over a built-in collection is enough. Every modern language already has this pattern built in.
  • You need random access by position (give me item 7). An iterator only moves step by step.

Where it shows up in LLD

  • Playlist or music player: next, previous, shuffle iterators.
  • Library or catalogue with filtered views.
  • Tree traversals (in-order, BFS) in a File System design.

Going deeper SDE-2 and SDE-3

  • This pattern is so common that languages absorbed it: Java Iterable/Iterator, Python __iter__/__next__ and generators, JS Symbol.iterator, C++ begin()/end(). Writing one by hand is mostly for custom structures.
  • Generators (yield) are iterators that write themselves and are lazy: they produce values on demand, which allows endless sequences.
  • Modifying a collection while iterating over it causes bugs (Java's ConcurrentModificationException). Decide if your iterator is fail-fast or works on a snapshot.
  • External iterators (the caller drives with next()) versus internal iterators (you pass a callback, like forEach).

Common mistakes

  • Changing the collection during iteration.
  • Sharing one iterator between callers.
Behavioral

Mediator

Have objects talk through a go-between instead of directly to each other, to stop a web of connections forming.

Explain it like I am new

An air traffic controller. Pilots do not talk to every other plane. Each one talks to the tower and the tower coordinates everyone. Add a plane and only the tower needs to know.

The problem

In a chat room, if every user holds a reference to every other user, ten users means ninety links. Adding a user means touching all the others, and no part can be reused alone.

The idea

Introduce a Mediator object. Every participant knows only the mediator and sends messages to it. The mediator decides who receives what. Participants become independent and the complicated rules live in one place.

Mediator class diagram<<interface>>ChatRoom+send(from, text)User AshaUser RaviUser Meera
Users know only the chat room. The room forwards each message to the right people.

See it in code

Three users talk through a chat room. A message goes to everyone except its sender.

Python · main.py

class ChatRoom:  # the mediator
    def __init__(self):
        self.users = []

    def join(self, user):
        self.users.append(user)
        user.room = self

    def send(self, sender, text):
        for user in self.users:
            if user is not sender:
                user.receive(sender.name, text)


class User:
    def __init__(self, name):
        self.name, self.room = name, None

    def say(self, text):
        self.room.send(self, text)  # talks to the room, not to other users

    def receive(self, from_name, text):
        print(f"{self.name} got {text} from {from_name}")


room = ChatRoom()
asha, ravi, meera = User("Asha"), User("Ravi"), User("Meera")
for user in (asha, ravi, meera):
    room.join(user)

asha.say("hello")
ravi.say("hi")

Java · Main.java

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

public class Main {
    public static void main(String[] args) {
        ChatRoom room = new ChatRoom();
        User asha = new User("Asha"), ravi = new User("Ravi"), meera = new User("Meera");
        room.join(asha); room.join(ravi); room.join(meera);

        asha.say("hello");
        ravi.say("hi");
    }
}

class ChatRoom { // the mediator
    private final List<User> users = new ArrayList<>();

    void join(User user) { users.add(user); user.room = this; }

    void send(User sender, String text) {
        for (User user : users) if (user != sender) user.receive(sender.name, text);
    }
}

class User {
    final String name;
    ChatRoom room;

    User(String name) { this.name = name; }
    void say(String text) { room.send(this, text); } // talks to the room, not to other users
    void receive(String from, String text) { System.out.println(name + " got " + text + " from " + from); }
}

C++ · main.cpp

#include <iostream>
#include <string>
#include <vector>

class User;

class ChatRoom {  // the mediator
public:
    void join(User* user);
    void send(const User* sender, const std::string& text) const;

private:
    std::vector<User*> users_;
};

class User {
public:
    explicit User(std::string name) : name_(std::move(name)) {}
    const std::string& name() const { return name_; }
    void say(const std::string& text) const { room_->send(this, text); }  // talks to the room, not to users
    void receive(const std::string& from, const std::string& text) const {
        std::cout << name_ << " got " << text << " from " << from << "\n";
    }
    ChatRoom* room_ = nullptr;

private:
    std::string name_;
};

void ChatRoom::join(User* user) { users_.push_back(user); user->room_ = this; }
void ChatRoom::send(const User* sender, const std::string& text) const {
    for (const User* user : users_)
        if (user != sender) user->receive(sender->name(), text);
}

int main() {
    ChatRoom room;
    User asha("Asha"), ravi("Ravi"), meera("Meera");
    room.join(&asha);
    room.join(&ravi);
    room.join(&meera);

    asha.say("hello");
    ravi.say("hi");
}

JavaScript · main.js

class ChatRoom { // the mediator
  users = [];
  join(user) { this.users.push(user); user.room = this; }
  send(sender, text) {
    for (const user of this.users) if (user !== sender) user.receive(sender.name, text);
  }
}

class User {
  constructor(name) { this.name = name; this.room = null; }
  say(text) { this.room.send(this, text); } // talks to the room, not to other users
  receive(from, text) { console.log(`${this.name} got ${text} from ${from}`); }
}

const room = new ChatRoom();
const asha = new User("Asha"), ravi = new User("Ravi"), meera = new User("Meera");
[asha, ravi, meera].forEach((u) => room.join(u));

asha.say("hello");
ravi.say("hi");

Go · main.go

package main

import "fmt"

type ChatRoom struct{ users []*User } // the mediator

type User struct {
	name string
	room *ChatRoom
}

func (r *ChatRoom) Join(u *User) {
	r.users = append(r.users, u)
	u.room = r
}

func (r *ChatRoom) Send(sender *User, text string) {
	for _, u := range r.users {
		if u != sender {
			u.Receive(sender.name, text)
		}
	}
}

func (u *User) Say(text string) { u.room.Send(u, text) } // talks to the room, not to other users
func (u *User) Receive(from, text string) {
	fmt.Printf("%s got %s from %s\n", u.name, text, from)
}

func main() {
	room := &ChatRoom{}
	asha, ravi, meera := &User{name: "Asha"}, &User{name: "Ravi"}, &User{name: "Meera"}
	room.Join(asha)
	room.Join(ravi)
	room.Join(meera)

	asha.Say("hello")
	ravi.Say("hi")
}
Output (identical in all five languages)
Ravi got hello from Asha
Meera got hello from Asha
Asha got hi from Ravi
Meera got hi from Ravi

Use it when

  • Many objects interact in complex ways and the connections are getting tangled.
  • You want to reuse components without dragging their neighbours along.
  • Interaction rules (who sees what) change often.

Skip it when

  • Only two objects talk. Let them talk directly.
  • The mediator would become a giant class that knows everything (a god object).

Where it shows up in LLD

  • Chat room or group messaging.
  • Air traffic control or an Elevator controller coordinating cars.
  • UI forms where widgets enable or disable each other.

Going deeper SDE-2 and SDE-3

  • The cost: the mediator concentrates complexity. Keep it focused or it becomes a god object.
  • Mediator versus Observer: with Observer, the subject broadcasts and listeners decide; with Mediator, a central object routes by rules. Event buses and message brokers lie between the two.
  • Real examples: Redux store, MVC controllers, a message broker like Kafka between services, Android Dispatchers.
  • Mediator versus Facade: Facade is one-way (client to subsystem), Mediator is two-way between peers.

Common mistakes

  • A mediator that holds all the logic.
  • Participants that sneak around the mediator and talk directly.
Behavioral

Memento

Save a snapshot of an object's state so you can restore it later, without exposing its internals.

Explain it like I am new

A save point in a video game. You can come back to that exact moment, and the game does not reveal how it stores your progress to anyone else.

The problem

You want undo in a text editor. To restore the earlier text, something has to copy the editor's private state. If outsiders can read and write that state, you have broken encapsulation.

The idea

Let the object itself create a Memento: an opaque snapshot of its state. A separate Caretaker keeps the mementos (for example on an undo stack) but cannot look inside. To undo, the caretaker hands a memento back and the object restores itself.

Memento class diagramEditor (Originator)-text+save(): Memento+restore(m)Memento-text (read only)History (Caretaker)-stack: Memento[]createsstores
The editor creates snapshots, the history keeps them, and only the editor can read them.

See it in code

An editor saves a snapshot, keeps typing, and then undoes back to the saved text.

Python · main.py

class Memento:  # an opaque snapshot; the history never looks inside
    def __init__(self, text):
        self._text = text


class Editor:
    def __init__(self):
        self.text = ""

    def type(self, more):
        self.text += more

    def save(self):
        return Memento(self.text)

    def restore(self, memento):
        self.text = memento._text


editor, history = Editor(), []
editor.type("Hello")
history.append(editor.save())  # checkpoint
editor.type(" World")
print("text:", editor.text)

editor.restore(history.pop())  # undo
print("after undo:", editor.text)

Java · Main.java

import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    public static void main(String[] args) {
        Editor editor = new Editor();
        Deque<Editor.Memento> history = new ArrayDeque<>();

        editor.type("Hello");
        history.push(editor.save()); // checkpoint
        editor.type(" World");
        System.out.println("text: " + editor.text());

        editor.restore(history.pop()); // undo
        System.out.println("after undo: " + editor.text());
    }
}

class Editor {
    private String text = "";

    void type(String more) { text += more; }
    String text() { return text; }

    Memento save() { return new Memento(text); }
    void restore(Memento m) { text = m.text; }

    // Nested and private-field: only the Editor can read what is inside.
    static class Memento {
        private final String text;
        private Memento(String text) { this.text = text; }
    }
}

C++ · main.cpp

#include <iostream>
#include <stack>
#include <string>

class Editor {
public:
    class Memento {  // only Editor can read it (friend), everyone else just holds it
        friend class Editor;
        explicit Memento(std::string t) : text_(std::move(t)) {}
        std::string text_;
    };

    void type(const std::string& more) { text_ += more; }
    const std::string& text() const { return text_; }
    Memento save() const { return Memento(text_); }
    void restore(const Memento& m) { text_ = m.text_; }

private:
    std::string text_;
};

int main() {
    Editor editor;
    std::stack<Editor::Memento> history;

    editor.type("Hello");
    history.push(editor.save());  // checkpoint
    editor.type(" World");
    std::cout << "text: " << editor.text() << "\n";

    editor.restore(history.top());  // undo
    history.pop();
    std::cout << "after undo: " << editor.text() << "\n";
}

JavaScript · main.js

class Editor {
  #text = "";

  type(more) { this.#text += more; }
  get text() { return this.#text; }

  save() { return Object.freeze({ text: this.#text }); } // an immutable snapshot
  restore(memento) { this.#text = memento.text; }
}

const editor = new Editor();
const history = [];

editor.type("Hello");
history.push(editor.save()); // checkpoint
editor.type(" World");
console.log("text:", editor.text);

editor.restore(history.pop()); // undo
console.log("after undo:", editor.text);

Go · main.go

package main

import "fmt"

// Memento is exported but its field is not, so other packages can hold it without reading it.
type Memento struct{ text string }

type Editor struct{ text string }

func (e *Editor) Type(more string)      { e.text += more }
func (e *Editor) Save() Memento         { return Memento{e.text} }
func (e *Editor) Restore(m Memento)     { e.text = m.text }

func main() {
	editor := &Editor{}
	var history []Memento

	editor.Type("Hello")
	history = append(history, editor.Save()) // checkpoint
	editor.Type(" World")
	fmt.Println("text:", editor.text)

	editor.Restore(history[len(history)-1]) // undo
	history = history[:len(history)-1]
	fmt.Println("after undo:", editor.text)
}
Output (identical in all five languages)
text: Hello World
after undo: Hello

Use it when

  • You need undo, rollback or checkpoints.
  • A direct copy of the state would expose private details.

Skip it when

  • State is huge and snapshots would use too much memory. Store changes (Command with inverse) instead.
  • State is trivial. A copy of a value is enough.

Where it shows up in LLD

  • Text editor undo.
  • Game save and load, Chess/Tic-Tac-Toe move history.
  • Database transaction rollback, form drafts.

Going deeper SDE-2 and SDE-3

  • Memento versus Command for undo: Memento stores whole states (simple, memory heavy), Command stores operations (compact, but every operation needs a correct inverse). Many editors use both.
  • Snapshots can be made smaller by storing only the difference, or by structural sharing (immutable data).
  • Keep a limit on history size.
  • Three roles: Originator (creates and restores), Memento (the snapshot, immutable) and Caretaker (stores them).

Common mistakes

  • Making the memento mutable.
  • Unbounded history.
Behavioral

Observer

Let objects subscribe to another object and be told automatically whenever it changes.

Explain it like I am new

A YouTube channel. You subscribe once, and every time there is a new video you are notified. The channel does not know who you are, only that someone wants to hear about uploads. You can unsubscribe at any time.

The problem

A stock price changes and five different screens, an alert system and a logger all need to react. If the price object calls each of them by name, it depends on all of them, and adding a new listener means editing it.

The idea

The object being watched (the subject) keeps a list of observers and has subscribe/unsubscribe. When it changes, it loops over the list and calls update() on each. Observers register themselves; the subject only knows the observer interface.

Observer class diagramStockTicker (Subject)-observers: List+subscribe(o)+unsubscribe(o)+setPrice(p)<<interface>>Observer+update(symbol, price)AliceBobnotifies
The ticker only knows the Observer interface. Anyone who implements it can subscribe.

See it in code

Two people subscribe to a stock. One unsubscribes, and only the other sees the next price.

Python · main.py

class StockTicker:  # the subject
    def __init__(self, symbol):
        self.symbol, self._observers = symbol, []

    def subscribe(self, observer):
        self._observers.append(observer)

    def unsubscribe(self, observer):
        self._observers.remove(observer)

    def set_price(self, price):
        for observer in self._observers:
            observer.update(self.symbol, price)  # tell everyone


class Person:
    def __init__(self, name):
        self.name = name

    def update(self, symbol, price):
        print(f"{self.name} sees {symbol} at {price}")


ticker = StockTicker("INFY")
alice, bob = Person("Alice"), Person("Bob")
ticker.subscribe(alice)
ticker.subscribe(bob)

ticker.set_price(100)
ticker.unsubscribe(bob)
ticker.set_price(105)

Java · Main.java

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

public class Main {
    public static void main(String[] args) {
        StockTicker ticker = new StockTicker("INFY");
        Person alice = new Person("Alice"), bob = new Person("Bob");
        ticker.subscribe(alice);
        ticker.subscribe(bob);

        ticker.setPrice(100);
        ticker.unsubscribe(bob);
        ticker.setPrice(105);
    }
}

interface Observer { void update(String symbol, int price); }

class StockTicker { // the subject
    private final String symbol;
    private final List<Observer> observers = new ArrayList<>();

    StockTicker(String symbol) { this.symbol = symbol; }
    void subscribe(Observer o) { observers.add(o); }
    void unsubscribe(Observer o) { observers.remove(o); }

    void setPrice(int price) {
        for (Observer o : observers) o.update(symbol, price); // tell everyone
    }
}

class Person implements Observer {
    private final String name;
    Person(String name) { this.name = name; }
    public void update(String symbol, int price) { System.out.println(name + " sees " + symbol + " at " + price); }
}

C++ · main.cpp

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

struct Observer {
    virtual ~Observer() = default;
    virtual void update(const std::string& symbol, int price) = 0;
};

class StockTicker {  // the subject
public:
    explicit StockTicker(std::string symbol) : symbol_(std::move(symbol)) {}
    void subscribe(Observer* o) { observers_.push_back(o); }
    void unsubscribe(Observer* o) { observers_.erase(std::remove(observers_.begin(), observers_.end(), o), observers_.end()); }
    void setPrice(int price) {
        for (Observer* o : observers_) o->update(symbol_, price);  // tell everyone
    }

private:
    std::string symbol_;
    std::vector<Observer*> observers_;
};

class Person : public Observer {
public:
    explicit Person(std::string name) : name_(std::move(name)) {}
    void update(const std::string& symbol, int price) override {
        std::cout << name_ << " sees " << symbol << " at " << price << "\n";
    }

private:
    std::string name_;
};

int main() {
    StockTicker ticker("INFY");
    Person alice("Alice"), bob("Bob");
    ticker.subscribe(&alice);
    ticker.subscribe(&bob);

    ticker.setPrice(100);
    ticker.unsubscribe(&bob);
    ticker.setPrice(105);
}

JavaScript · main.js

class StockTicker { // the subject
  observers = [];
  constructor(symbol) { this.symbol = symbol; }
  subscribe(observer) { this.observers.push(observer); }
  unsubscribe(observer) { this.observers = this.observers.filter((o) => o !== observer); }
  setPrice(price) {
    for (const observer of this.observers) observer.update(this.symbol, price); // tell everyone
  }
}

class Person {
  constructor(name) { this.name = name; }
  update(symbol, price) { console.log(`${this.name} sees ${symbol} at ${price}`); }
}

const ticker = new StockTicker("INFY");
const alice = new Person("Alice"), bob = new Person("Bob");
ticker.subscribe(alice);
ticker.subscribe(bob);

ticker.setPrice(100);
ticker.unsubscribe(bob);
ticker.setPrice(105);

Go · main.go

package main

import "fmt"

type Observer interface{ Update(symbol string, price int) }

type StockTicker struct { // the subject
	symbol    string
	observers []Observer
}

func (t *StockTicker) Subscribe(o Observer) { t.observers = append(t.observers, o) }

func (t *StockTicker) Unsubscribe(o Observer) {
	for i, x := range t.observers {
		if x == o {
			t.observers = append(t.observers[:i], t.observers[i+1:]...)
			return
		}
	}
}

func (t *StockTicker) SetPrice(price int) {
	for _, o := range t.observers {
		o.Update(t.symbol, price) // tell everyone
	}
}

type Person struct{ name string }

func (p *Person) Update(symbol string, price int) {
	fmt.Printf("%s sees %s at %d\n", p.name, symbol, price)
}

func main() {
	ticker := &StockTicker{symbol: "INFY"}
	alice, bob := &Person{"Alice"}, &Person{"Bob"}
	ticker.Subscribe(alice)
	ticker.Subscribe(bob)

	ticker.SetPrice(100)
	ticker.Unsubscribe(bob)
	ticker.SetPrice(105)
}
Output (identical in all five languages)
Alice sees INFY at 100
Bob sees INFY at 100
Alice sees INFY at 105

Use it when

  • A change in one object must trigger updates in others, and you do not know how many.
  • You want loose coupling between the thing that changes and the things that react.
  • Event systems, UI data binding, notifications.

Skip it when

  • Only one fixed listener exists. Call it directly.
  • The notification order or timing is critical and hard to reason about.

Where it shows up in LLD

  • Notification System, Stock ticker, YouTube subscriptions.
  • Online Auction: bidders notified of new highest bid.
  • Weather station, Cricket scoreboard, Food delivery order status updates.

Going deeper SDE-2 and SDE-3

  • Push versus pull: push sends the new data to observers in the call, pull only says 'something changed' and observers ask for what they need.
  • Memory leaks: subjects hold strong references to observers, so forgetting to unsubscribe keeps them alive (the lapsed listener problem). Use weak references or explicit lifecycle.
  • Threading: notifications from another thread, observers that throw, and observers that subscribe or unsubscribe during a notification all need decisions.
  • Pub/Sub with a broker (Kafka, Redis, an event bus) is Observer across processes, with a topic in the middle for decoupling.

Common mistakes

  • Update storms: observer A changes the subject, which notifies A again.
  • Forgetting to unsubscribe.
Behavioral

State

Let an object change its behaviour when its internal state changes, by moving each state into its own class.

Explain it like I am new

A traffic light or a vending machine. The same button does different things depending on the state: pressing it with no coin does nothing useful, with a coin it gives you a snack.

The problem

A vending machine has states (no coin, has coin, sold out) and each action (insert coin, press button) must behave differently per state. The usual answer is giant if state == ... blocks in every method, which grow and break whenever a state is added.

The idea

Make each state its own class implementing the same interface (insertCoin, pressButton). The machine holds a reference to its current state object and forwards every action to it. A state decides what happens and swaps the machine to the next state.

State class diagramVendingMachine-state: State+insertCoin()+pressButton()<<interface>>State+insertCoin()+pressButton()NoCoinHasCoindelegatescoin
The machine passes each action to its current state object. States switch the machine to the next state.

See it in code

A vending machine reacts to the same two actions differently depending on whether a coin was inserted.

Python · main.py

class NoCoin:
    def insert_coin(self, machine):
        print("coin accepted")
        machine.state = HasCoin()

    def press_button(self, machine):
        print("insert a coin first")


class HasCoin:
    def insert_coin(self, machine):
        print("already have a coin")

    def press_button(self, machine):
        print("here is your snack")
        machine.state = NoCoin()  # back to the start


class VendingMachine:
    def __init__(self):
        self.state = NoCoin()

    def insert_coin(self): self.state.insert_coin(self)
    def press_button(self): self.state.press_button(self)


machine = VendingMachine()
machine.press_button()
machine.insert_coin()
machine.insert_coin()
machine.press_button()
machine.press_button()

Java · Main.java

public class Main {
    public static void main(String[] args) {
        VendingMachine machine = new VendingMachine();
        machine.pressButton();
        machine.insertCoin();
        machine.insertCoin();
        machine.pressButton();
        machine.pressButton();
    }
}

interface State {
    void insertCoin(VendingMachine m);
    void pressButton(VendingMachine m);
}

class NoCoin implements State {
    public void insertCoin(VendingMachine m) { System.out.println("coin accepted"); m.state = new HasCoin(); }
    public void pressButton(VendingMachine m) { System.out.println("insert a coin first"); }
}

class HasCoin implements State {
    public void insertCoin(VendingMachine m) { System.out.println("already have a coin"); }
    public void pressButton(VendingMachine m) { System.out.println("here is your snack"); m.state = new NoCoin(); }
}

class VendingMachine {
    State state = new NoCoin();
    void insertCoin() { state.insertCoin(this); }
    void pressButton() { state.pressButton(this); }
}

C++ · main.cpp

#include <iostream>
#include <memory>

class VendingMachine;

struct State {
    virtual ~State() = default;
    virtual void insertCoin(VendingMachine& m) = 0;
    virtual void pressButton(VendingMachine& m) = 0;
};

class VendingMachine {
public:
    VendingMachine();
    void insertCoin() { state->insertCoin(*this); }
    void pressButton() { state->pressButton(*this); }
    std::unique_ptr<State> state;
};

struct NoCoin : State {
    void insertCoin(VendingMachine& m) override;
    void pressButton(VendingMachine&) override { std::cout << "insert a coin first\n"; }
};

struct HasCoin : State {
    void insertCoin(VendingMachine&) override { std::cout << "already have a coin\n"; }
    void pressButton(VendingMachine& m) override {
        std::cout << "here is your snack\n";
        m.state = std::make_unique<NoCoin>();  // back to the start
    }
};

VendingMachine::VendingMachine() : state(std::make_unique<NoCoin>()) {}

void NoCoin::insertCoin(VendingMachine& m) {
    std::cout << "coin accepted\n";
    m.state = std::make_unique<HasCoin>();
}

int main() {
    VendingMachine machine;
    machine.pressButton();
    machine.insertCoin();
    machine.insertCoin();
    machine.pressButton();
    machine.pressButton();
}

JavaScript · main.js

class NoCoin {
  insertCoin(machine) { console.log("coin accepted"); machine.state = new HasCoin(); }
  pressButton() { console.log("insert a coin first"); }
}

class HasCoin {
  insertCoin() { console.log("already have a coin"); }
  pressButton(machine) { console.log("here is your snack"); machine.state = new NoCoin(); } // back to the start
}

class VendingMachine {
  state = new NoCoin();
  insertCoin() { this.state.insertCoin(this); }
  pressButton() { this.state.pressButton(this); }
}

const machine = new VendingMachine();
machine.pressButton();
machine.insertCoin();
machine.insertCoin();
machine.pressButton();
machine.pressButton();

Go · main.go

package main

import "fmt"

type State interface {
	InsertCoin(m *VendingMachine)
	PressButton(m *VendingMachine)
}

type VendingMachine struct{ state State }

func (m *VendingMachine) InsertCoin()  { m.state.InsertCoin(m) }
func (m *VendingMachine) PressButton() { m.state.PressButton(m) }

type NoCoin struct{}
type HasCoin struct{}

func (NoCoin) InsertCoin(m *VendingMachine) {
	fmt.Println("coin accepted")
	m.state = HasCoin{}
}
func (NoCoin) PressButton(m *VendingMachine) { fmt.Println("insert a coin first") }

func (HasCoin) InsertCoin(m *VendingMachine) { fmt.Println("already have a coin") }
func (HasCoin) PressButton(m *VendingMachine) {
	fmt.Println("here is your snack")
	m.state = NoCoin{} // back to the start
}

func main() {
	machine := &VendingMachine{state: NoCoin{}}
	machine.PressButton()
	machine.InsertCoin()
	machine.InsertCoin()
	machine.PressButton()
	machine.PressButton()
}
Output (identical in all five languages)
insert a coin first
coin accepted
already have a coin
here is your snack
insert a coin first

Use it when

  • An object behaves very differently depending on its state and has many states.
  • Your code is full of large if/else or switch statements on a state field.
  • State transitions follow clear rules.

Skip it when

  • Only two or three simple states with a little logic. An enum and a switch is simpler.
  • State changes rarely.

Where it shows up in LLD

  • Vending Machine, ATM (idle, card inserted, pin entered, dispensing).
  • Elevator (idle, moving up, moving down, doors open).
  • Order lifecycle (placed, paid, shipped, delivered) and Traffic signal, Document workflow.

Going deeper SDE-2 and SDE-3

  • State versus Strategy: identical in structure, different in intent. Strategy is chosen by the client and rarely changes. State changes itself as the object runs, and states often know about each other.
  • Where do transitions live: inside the state classes (decentralised, easy to extend) or in a table in the context (central, easy to see the whole machine)?
  • State objects can be shared (flyweight) if they hold no data of their own.
  • For big machines, draw the state diagram first. Interviewers usually want to see it.

Common mistakes

  • Invalid transitions that are silently allowed.
  • State classes that need too much of the context's data.
Behavioral

Strategy

Put each way of doing something in its own class, so you can swap them without touching the code that uses them.

Explain it like I am new

Getting to the airport. You can take a bus, a taxi or the metro. The goal is the same, the way differs, and you can choose a different one depending on time and money.

The problem

Shipping cost is calculated differently for standard, express and pickup, and new options keep arriving. Putting it all in one method with if method == 'express' ... else if ... makes the method huge and risky to change.

The idea

Define a small interface for the changing step (cost(weight)). Write one class per algorithm. The class that needs the step holds a reference to the interface and just calls it. Pick or change the strategy at runtime.

Strategy class diagramCheckout-strategy: ShippingStrategy+cost(weight)<<interface>>ShippingStrategy+cost(weight): intStandardExpressPickupuses
Checkout holds a strategy and calls it. Swapping the strategy changes the behaviour.

See it in code

The same shipping cost call gives a different price depending on which strategy is set.

Python · main.py

class Standard:
    def cost(self, weight): return 40


class Express:
    def cost(self, weight): return weight * 20 + 100


class Pickup:
    def cost(self, weight): return 0


class Checkout:
    def __init__(self, strategy):
        self.strategy = strategy

    def shipping(self, weight):
        return self.strategy.cost(weight)  # the checkout does not know which algorithm runs


checkout = Checkout(Standard())
print("standard: Rs", checkout.shipping(3))

checkout.strategy = Express()  # switch at runtime
print("express: Rs", checkout.shipping(3))

checkout.strategy = Pickup()
print("pickup: Rs", checkout.shipping(3))

Java · Main.java

public class Main {
    public static void main(String[] args) {
        Checkout checkout = new Checkout(new Standard());
        System.out.println("standard: Rs " + checkout.shipping(3));

        checkout.setStrategy(new Express()); // switch at runtime
        System.out.println("express: Rs " + checkout.shipping(3));

        checkout.setStrategy(new Pickup());
        System.out.println("pickup: Rs " + checkout.shipping(3));
    }
}

interface ShippingStrategy { int cost(int weight); }
class Standard implements ShippingStrategy { public int cost(int w) { return 40; } }
class Express implements ShippingStrategy { public int cost(int w) { return w * 20 + 100; } }
class Pickup implements ShippingStrategy { public int cost(int w) { return 0; } }

class Checkout {
    private ShippingStrategy strategy;
    Checkout(ShippingStrategy s) { strategy = s; }
    void setStrategy(ShippingStrategy s) { strategy = s; }
    int shipping(int weight) { return strategy.cost(weight); } // does not know which algorithm runs
}

C++ · main.cpp

#include <iostream>
#include <memory>

struct ShippingStrategy {
    virtual ~ShippingStrategy() = default;
    virtual int cost(int weight) const = 0;
};
struct Standard : ShippingStrategy { int cost(int) const override { return 40; } };
struct Express : ShippingStrategy { int cost(int w) const override { return w * 20 + 100; } };
struct Pickup : ShippingStrategy { int cost(int) const override { return 0; } };

class Checkout {
public:
    explicit Checkout(std::unique_ptr<ShippingStrategy> s) : strategy_(std::move(s)) {}
    void setStrategy(std::unique_ptr<ShippingStrategy> s) { strategy_ = std::move(s); }
    int shipping(int weight) const { return strategy_->cost(weight); }  // does not know which algorithm runs

private:
    std::unique_ptr<ShippingStrategy> strategy_;
};

int main() {
    Checkout checkout(std::make_unique<Standard>());
    std::cout << "standard: Rs " << checkout.shipping(3) << "\n";

    checkout.setStrategy(std::make_unique<Express>());  // switch at runtime
    std::cout << "express: Rs " << checkout.shipping(3) << "\n";

    checkout.setStrategy(std::make_unique<Pickup>());
    std::cout << "pickup: Rs " << checkout.shipping(3) << "\n";
}

JavaScript · main.js

// In JavaScript a strategy can simply be a function.
const standard = () => 40;
const express = (weight) => weight * 20 + 100;
const pickup = () => 0;

class Checkout {
  constructor(strategy) { this.strategy = strategy; }
  shipping(weight) { return this.strategy(weight); } // does not know which algorithm runs
}

const checkout = new Checkout(standard);
console.log("standard: Rs", checkout.shipping(3));

checkout.strategy = express; // switch at runtime
console.log("express: Rs", checkout.shipping(3));

checkout.strategy = pickup;
console.log("pickup: Rs", checkout.shipping(3));

Go · main.go

package main

import "fmt"

type ShippingStrategy interface{ Cost(weight int) int }

type Standard struct{}
type Express struct{}
type Pickup struct{}

func (Standard) Cost(w int) int { return 40 }
func (Express) Cost(w int) int  { return w*20 + 100 }
func (Pickup) Cost(w int) int   { return 0 }

type Checkout struct{ strategy ShippingStrategy }

func (c Checkout) Shipping(weight int) int { return c.strategy.Cost(weight) } // does not know which runs

func main() {
	checkout := Checkout{Standard{}}
	fmt.Println("standard: Rs", checkout.Shipping(3))

	checkout.strategy = Express{} // switch at runtime
	fmt.Println("express: Rs", checkout.Shipping(3))

	checkout.strategy = Pickup{}
	fmt.Println("pickup: Rs", checkout.Shipping(3))
}
Output (identical in all five languages)
standard: Rs 40
express: Rs 160
pickup: Rs 0

Use it when

  • You have several ways to do the same task and want to switch between them.
  • A class has big conditionals choosing between behaviours.
  • You want to test each algorithm alone.

Skip it when

  • Only one algorithm will ever exist.
  • The variations are tiny. A function parameter might be enough.

Where it shows up in LLD

  • Parking Lot: pricing by hour, by day or flat fee.
  • Payment methods (card, UPI, wallet), shipping cost, discount rules.
  • Elevator scheduling and driver-matching (nearest, fastest) in Ride Sharing.
  • Chess AI levels, sorting or compression algorithm choice.

Going deeper SDE-2 and SDE-3

  • In languages with first-class functions, a strategy can simply be a function or lambda: cost = lambda w: w*20 + 100. Classes are for when a strategy has its own state or several methods.
  • Strategy versus State: same structure. A client picks a Strategy, a State changes itself. Strategy versus Bridge: Strategy swaps one algorithm, Bridge keeps two whole hierarchies independent.
  • Strategy is the Open/Closed principle in the simplest form: add a new class, change nothing else.
  • Selecting the strategy still needs a decision somewhere. Often a factory or a config does that, so the if statement moves to one place instead of many.

Common mistakes

  • Clients that must know too much about each strategy.
  • One class per trivial algorithm, creating pointless classes.
Behavioral

Template Method

Fix the order of steps in a base class and let subclasses fill in some of the steps.

Explain it like I am new

A recipe template: wash, chop, cook, serve. Every dish follows the same order, but 'cook' means frying for one dish and boiling for another.

The problem

Reading a CSV and reading a JSON file follow the same flow: open, extract, parse, report. If each has its own copy of the whole flow, the shared parts are duplicated and drift apart.

The idea

Put the whole algorithm in one method of a base class (the template method). Fixed steps are implemented there. Steps that vary are abstract (or have default hooks) and subclasses override only those. The base class controls the order, subclasses cannot change it.

Template Method class diagram<<abstract>>DataMiner+mine() (template: fixed order)#open()#extract()#parse()-report()CsvMinerJsonMiner
mine() fixes the order. CsvMiner and JsonMiner only supply the steps that differ.

See it in code

Two data miners share the same four steps. Only the opening, extracting and parsing differ.

Python · main.py

from abc import ABC, abstractmethod


class DataMiner(ABC):
    def mine(self):  # the template method: the order never changes
        self.open()
        self.extract()
        self.parse()
        print("report ready")

    @abstractmethod
    def open(self): ...

    @abstractmethod
    def extract(self): ...

    @abstractmethod
    def parse(self): ...


class CsvMiner(DataMiner):
    def open(self): print("opening csv file")
    def extract(self): print("extracting rows")
    def parse(self): print("parsing with commas")


class JsonMiner(DataMiner):
    def open(self): print("opening json file")
    def extract(self): print("extracting objects")
    def parse(self): print("parsing with brackets")


CsvMiner().mine()
print("---")
JsonMiner().mine()

Java · Main.java

public class Main {
    public static void main(String[] args) {
        new CsvMiner().mine();
        System.out.println("---");
        new JsonMiner().mine();
    }
}

abstract class DataMiner {
    final void mine() { // the template method: the order never changes
        open();
        extract();
        parse();
        System.out.println("report ready");
    }

    abstract void open();
    abstract void extract();
    abstract void parse();
}

class CsvMiner extends DataMiner {
    void open() { System.out.println("opening csv file"); }
    void extract() { System.out.println("extracting rows"); }
    void parse() { System.out.println("parsing with commas"); }
}

class JsonMiner extends DataMiner {
    void open() { System.out.println("opening json file"); }
    void extract() { System.out.println("extracting objects"); }
    void parse() { System.out.println("parsing with brackets"); }
}

C++ · main.cpp

#include <iostream>

class DataMiner {
public:
    virtual ~DataMiner() = default;
    void mine() {  // the template method: the order never changes
        open();
        extract();
        parse();
        std::cout << "report ready\n";
    }

protected:
    virtual void open() = 0;
    virtual void extract() = 0;
    virtual void parse() = 0;
};

class CsvMiner : public DataMiner {
protected:
    void open() override { std::cout << "opening csv file\n"; }
    void extract() override { std::cout << "extracting rows\n"; }
    void parse() override { std::cout << "parsing with commas\n"; }
};

class JsonMiner : public DataMiner {
protected:
    void open() override { std::cout << "opening json file\n"; }
    void extract() override { std::cout << "extracting objects\n"; }
    void parse() override { std::cout << "parsing with brackets\n"; }
};

int main() {
    CsvMiner().mine();
    std::cout << "---\n";
    JsonMiner().mine();
}

JavaScript · main.js

class DataMiner {
  mine() { // the template method: the order never changes
    this.open();
    this.extract();
    this.parse();
    console.log("report ready");
  }
  open() { throw new Error("subclass must implement"); }
  extract() { throw new Error("subclass must implement"); }
  parse() { throw new Error("subclass must implement"); }
}

class CsvMiner extends DataMiner {
  open() { console.log("opening csv file"); }
  extract() { console.log("extracting rows"); }
  parse() { console.log("parsing with commas"); }
}

class JsonMiner extends DataMiner {
  open() { console.log("opening json file"); }
  extract() { console.log("extracting objects"); }
  parse() { console.log("parsing with brackets"); }
}

new CsvMiner().mine();
console.log("---");
new JsonMiner().mine();

Go · main.go

package main

import "fmt"

// Go has no inheritance, so the varying steps are an interface and the template is a function.
type Steps interface {
	Open()
	Extract()
	Parse()
}

func Mine(s Steps) { // the template: the order never changes
	s.Open()
	s.Extract()
	s.Parse()
	fmt.Println("report ready")
}

type CsvMiner struct{}
type JsonMiner struct{}

func (CsvMiner) Open()     { fmt.Println("opening csv file") }
func (CsvMiner) Extract()  { fmt.Println("extracting rows") }
func (CsvMiner) Parse()    { fmt.Println("parsing with commas") }
func (JsonMiner) Open()    { fmt.Println("opening json file") }
func (JsonMiner) Extract() { fmt.Println("extracting objects") }
func (JsonMiner) Parse()   { fmt.Println("parsing with brackets") }

func main() {
	Mine(CsvMiner{})
	fmt.Println("---")
	Mine(JsonMiner{})
}
Output (identical in all five languages)
opening csv file
extracting rows
parsing with commas
report ready
---
opening json file
extracting objects
parsing with brackets
report ready

Use it when

  • Several classes share the same overall steps but differ in a few of them.
  • You want to prevent subclasses from changing the order.
  • You want to remove duplicated code from similar classes.

Skip it when

  • The variation is in many places. The inheritance gets tangled, so prefer Strategy and composition.
  • You need to change the algorithm at runtime. Inheritance fixes it at compile time.

Where it shows up in LLD

  • Game turns (Chess, Tic-Tac-Toe): start, play turn, check winner, end.
  • Data import/export pipelines, report generators.
  • Beverage makers: boil water, brew, pour, add extras.

Going deeper SDE-2 and SDE-3

  • The Hollywood principle: 'don't call us, we'll call you'. The framework (base class) calls your code, not the other way round. Frameworks like JUnit setUp/tearDown and servlets work this way.
  • Hooks are optional steps with an empty default that subclasses may override.
  • It is a form of inheritance, so it suffers the same fragility. Strategy does the same job with composition and is easier to swap at runtime.
  • Factory Method is a template method whose varying step is 'create the object'.

Common mistakes

  • Too many abstract steps, making subclasses hard to write.
  • Subclasses that break the base class's assumptions.
Behavioral

Visitor

Add new operations to a group of classes without changing those classes, by sending a visitor object to each one.

Explain it like I am new

A tax inspector visiting different kinds of shops. The inspector does a different check at a bakery than at a bookshop, but the shops do not need new features to be inspected. They just let the inspector in.

The problem

A cart holds Books and Fruits. You want to compute tax, then discounts, then print an invoice, then export to JSON. Adding each operation as a method to every item class makes the items bloated, and every new operation means editing all of them.

The idea

Move each operation into a Visitor class with one method per item type (visitBook, visitFruit). Each item has one method, accept(visitor), which calls the visitor's method for its own type. The visitor learns the item's real type without any type checks (double dispatch). A new operation is a new visitor, and no item class changes.

Visitor class diagram<<interface>>Item+accept(visitor)BookFruit<<interface>>Visitor+visitBook(book)+visitFruit(fruit)TaxVisitorDiscountVisitoraccept calls visit
Each item calls back the visitor method for its own type. New operations are new visitors.

See it in code

Two visitors, tax and discount, run over the same books and fruits without changing the item classes.

Python · main.py

class Book:
    def __init__(self, price): self.price = price
    def accept(self, visitor): visitor.visit_book(self)


class Fruit:
    def __init__(self, price, kg): self.price, self.kg = price, kg
    def accept(self, visitor): visitor.visit_fruit(self)


class TaxVisitor:
    def visit_book(self, book): print("Book tax:", book.price * 12 // 100)
    def visit_fruit(self, fruit): print("Fruit tax:", fruit.price * fruit.kg * 5 // 100)


class DiscountVisitor:
    def visit_book(self, book): print("Book discount:", book.price * 10 // 100)
    def visit_fruit(self, fruit): print("Fruit discount:", fruit.price * fruit.kg * 10 // 100)


cart = [Book(500), Fruit(40, 3)]
for visitor in (TaxVisitor(), DiscountVisitor()):
    for item in cart:
        item.accept(visitor)  # the item says which visit method to call

Java · Main.java

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Item> cart = List.of(new Book(500), new Fruit(40, 3));
        for (Visitor visitor : new Visitor[]{new TaxVisitor(), new DiscountVisitor()})
            for (Item item : cart) item.accept(visitor); // the item says which visit method to call
    }
}

interface Item { void accept(Visitor v); }
interface Visitor {
    void visitBook(Book b);
    void visitFruit(Fruit f);
}

class Book implements Item {
    final int price;
    Book(int price) { this.price = price; }
    public void accept(Visitor v) { v.visitBook(this); }
}

class Fruit implements Item {
    final int price, kg;
    Fruit(int price, int kg) { this.price = price; this.kg = kg; }
    public void accept(Visitor v) { v.visitFruit(this); }
}

class TaxVisitor implements Visitor {
    public void visitBook(Book b) { System.out.println("Book tax: " + b.price * 12 / 100); }
    public void visitFruit(Fruit f) { System.out.println("Fruit tax: " + f.price * f.kg * 5 / 100); }
}

class DiscountVisitor implements Visitor {
    public void visitBook(Book b) { System.out.println("Book discount: " + b.price * 10 / 100); }
    public void visitFruit(Fruit f) { System.out.println("Fruit discount: " + f.price * f.kg * 10 / 100); }
}

C++ · main.cpp

#include <iostream>
#include <memory>
#include <vector>

struct Book;
struct Fruit;

struct Visitor {
    virtual ~Visitor() = default;
    virtual void visitBook(const Book& b) = 0;
    virtual void visitFruit(const Fruit& f) = 0;
};

struct Item {
    virtual ~Item() = default;
    virtual void accept(Visitor& v) const = 0;
};

struct Book : Item {
    int price;
    explicit Book(int p) : price(p) {}
    void accept(Visitor& v) const override { v.visitBook(*this); }
};

struct Fruit : Item {
    int price, kg;
    Fruit(int p, int k) : price(p), kg(k) {}
    void accept(Visitor& v) const override { v.visitFruit(*this); }
};

struct TaxVisitor : Visitor {
    void visitBook(const Book& b) override { std::cout << "Book tax: " << b.price * 12 / 100 << "\n"; }
    void visitFruit(const Fruit& f) override { std::cout << "Fruit tax: " << f.price * f.kg * 5 / 100 << "\n"; }
};

struct DiscountVisitor : Visitor {
    void visitBook(const Book& b) override { std::cout << "Book discount: " << b.price * 10 / 100 << "\n"; }
    void visitFruit(const Fruit& f) override { std::cout << "Fruit discount: " << f.price * f.kg * 10 / 100 << "\n"; }
};

int main() {
    std::vector<std::unique_ptr<Item>> cart;
    cart.push_back(std::make_unique<Book>(500));
    cart.push_back(std::make_unique<Fruit>(40, 3));

    TaxVisitor tax;
    DiscountVisitor discount;
    for (Visitor* visitor : {static_cast<Visitor*>(&tax), static_cast<Visitor*>(&discount)})
        for (const auto& item : cart) item->accept(*visitor);  // the item says which visit method to call
}

JavaScript · main.js

class Book {
  constructor(price) { this.price = price; }
  accept(visitor) { visitor.visitBook(this); }
}

class Fruit {
  constructor(price, kg) { this.price = price; this.kg = kg; }
  accept(visitor) { visitor.visitFruit(this); }
}

class TaxVisitor {
  visitBook(b) { console.log("Book tax:", Math.floor((b.price * 12) / 100)); }
  visitFruit(f) { console.log("Fruit tax:", Math.floor((f.price * f.kg * 5) / 100)); }
}

class DiscountVisitor {
  visitBook(b) { console.log("Book discount:", Math.floor((b.price * 10) / 100)); }
  visitFruit(f) { console.log("Fruit discount:", Math.floor((f.price * f.kg * 10) / 100)); }
}

const cart = [new Book(500), new Fruit(40, 3)];
for (const visitor of [new TaxVisitor(), new DiscountVisitor()]) {
  for (const item of cart) item.accept(visitor); // the item says which visit method to call
}

Go · main.go

package main

import "fmt"

type Visitor interface {
	VisitBook(b Book)
	VisitFruit(f Fruit)
}

type Item interface{ Accept(v Visitor) }

type Book struct{ Price int }
type Fruit struct{ Price, Kg int }

func (b Book) Accept(v Visitor)  { v.VisitBook(b) }
func (f Fruit) Accept(v Visitor) { v.VisitFruit(f) }

type TaxVisitor struct{}
type DiscountVisitor struct{}

func (TaxVisitor) VisitBook(b Book)   { fmt.Println("Book tax:", b.Price*12/100) }
func (TaxVisitor) VisitFruit(f Fruit) { fmt.Println("Fruit tax:", f.Price*f.Kg*5/100) }

func (DiscountVisitor) VisitBook(b Book)   { fmt.Println("Book discount:", b.Price*10/100) }
func (DiscountVisitor) VisitFruit(f Fruit) { fmt.Println("Fruit discount:", f.Price*f.Kg*10/100) }

func main() {
	cart := []Item{Book{500}, Fruit{40, 3}}
	for _, visitor := range []Visitor{TaxVisitor{}, DiscountVisitor{}} {
		for _, item := range cart {
			item.Accept(visitor) // the item says which visit method to call
		}
	}
}
Output (identical in all five languages)
Book tax: 60
Fruit tax: 6
Book discount: 50
Fruit discount: 12

Use it when

  • You have a stable set of classes and keep adding new operations on them.
  • The operations differ by class and do not belong inside the classes.
  • You want to keep unrelated operations apart (tax, export, print).

Skip it when

  • New classes are added often. Every visitor must then change, so Visitor is the wrong direction.
  • Only one or two simple operations exist.

Where it shows up in LLD

  • Shopping cart tax and discount calculation.
  • File System: compute size, search, export over files and folders (with Composite).
  • Compiler or Interpreter: type-check, print and optimize an expression tree.

Going deeper SDE-2 and SDE-3

  • Double dispatch is the key idea. A normal call picks the method by the receiver's type only. accept followed by visitX lets the choice depend on both the item type and the visitor type.
  • The trade-off is the opposite of ordinary methods: easy to add operations, hard to add new classes. This is the 'expression problem'. Know which side your design is on.
  • Languages with pattern matching or sum types (Rust, Kotlin sealed classes, Python 3.10 match, TypeScript unions) make Visitor much lighter.
  • Visitors often walk Composite trees, so accept also forwards the visitor to children.

Common mistakes

  • Using it when the class list is unstable.
  • Visitors needing private data, which forces you to widen the item API.

Everyday extras

These three are not in the Gang of Four book, yet interviewers expect you to know them. They solve problems you meet in almost every design.

Everyday extras

Object Pool

Keep a set of expensive objects ready, lend them out and take them back instead of creating and destroying them each time.

Explain it like I am new

A bike-sharing station. Bikes are made once, you borrow one, ride, and return it for the next person. If all bikes are out, you wait or walk.

The problem

Some objects are slow or costly to create: database connections, threads, large buffers, network sockets. Creating one per request wastes time and can exhaust the system.

The idea

Create a fixed number of objects up front (or lazily up to a limit). acquire() hands one out and marks it busy, release() puts it back. When none are free, the caller waits, fails fast or the pool grows up to a limit.

Object Pool class diagramClientConnectionPool-free: List<Connection>+acquire(): Connection+release(c)Connectionacquire / releaseholds
Clients borrow from the pool and give back. The pool owns the objects and keeps the free ones ready.

See it in code

A pool of two connections: borrow both, fail to borrow a third, return one and borrow again.

Python · main.py

class ConnectionPool:
    def __init__(self, size):
        self._free = [f"conn-{i}" for i in range(1, size + 1)]

    def acquire(self):
        return self._free.pop(0) if self._free else None

    def release(self, conn):
        self._free.append(conn)


pool = ConnectionPool(2)
for i in range(3):
    conn = pool.acquire()
    print(f"acquired {conn}" if conn else "no connection free")
    if i == 0:
        first = conn

pool.release(first)
print("released", first)
print("acquired", pool.acquire())

Java · Main.java

import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    public static void main(String[] args) {
        ConnectionPool pool = new ConnectionPool(2);
        String first = null;
        for (int i = 0; i < 3; i++) {
            String conn = pool.acquire();
            System.out.println(conn != null ? "acquired " + conn : "no connection free");
            if (i == 0) first = conn;
        }
        pool.release(first);
        System.out.println("released " + first);
        System.out.println("acquired " + pool.acquire());
    }
}

class ConnectionPool {
    private final Deque<String> free = new ArrayDeque<>();

    ConnectionPool(int size) { for (int i = 1; i <= size; i++) free.add("conn-" + i); }

    String acquire() { return free.pollFirst(); } // null when empty
    void release(String conn) { free.addLast(conn); }
}

C++ · main.cpp

#include <deque>
#include <iostream>
#include <optional>
#include <string>

class ConnectionPool {
public:
    explicit ConnectionPool(int size) {
        for (int i = 1; i <= size; i++) free_.push_back("conn-" + std::to_string(i));
    }
    std::optional<std::string> acquire() {
        if (free_.empty()) return std::nullopt;
        std::string c = free_.front();
        free_.pop_front();
        return c;
    }
    void release(const std::string& c) { free_.push_back(c); }

private:
    std::deque<std::string> free_;
};

int main() {
    ConnectionPool pool(2);
    std::string first;
    for (int i = 0; i < 3; i++) {
        auto conn = pool.acquire();
        if (conn) std::cout << "acquired " << *conn << "\n";
        else std::cout << "no connection free\n";
        if (i == 0) first = *conn;
    }
    pool.release(first);
    std::cout << "released " << first << "\n";
    std::cout << "acquired " << *pool.acquire() << "\n";
}

JavaScript · main.js

class ConnectionPool {
  #free;
  constructor(size) { this.#free = Array.from({ length: size }, (_, i) => `conn-${i + 1}`); }
  acquire() { return this.#free.shift() ?? null; } // null when empty
  release(conn) { this.#free.push(conn); }
}

const pool = new ConnectionPool(2);
let first;
for (let i = 0; i < 3; i++) {
  const conn = pool.acquire();
  console.log(conn ? `acquired ${conn}` : "no connection free");
  if (i === 0) first = conn;
}
pool.release(first);
console.log("released", first);
console.log("acquired", pool.acquire());

Go · main.go

package main

import "fmt"

type ConnectionPool struct{ free chan string } // a buffered channel is a ready-made pool

func NewPool(size int) *ConnectionPool {
	p := &ConnectionPool{free: make(chan string, size)}
	for i := 1; i <= size; i++ {
		p.free <- fmt.Sprintf("conn-%d", i)
	}
	return p
}

func (p *ConnectionPool) Acquire() (string, bool) {
	select {
	case c := <-p.free:
		return c, true
	default:
		return "", false // nothing free right now
	}
}

func (p *ConnectionPool) Release(c string) { p.free <- c }

func main() {
	pool := NewPool(2)
	first := ""
	for i := 0; i < 3; i++ {
		conn, ok := pool.Acquire()
		if ok {
			fmt.Println("acquired", conn)
		} else {
			fmt.Println("no connection free")
		}
		if i == 0 {
			first = conn
		}
	}
	pool.Release(first)
	fmt.Println("released", first)
	conn, _ := pool.Acquire()
	fmt.Println("acquired", conn)
}
Output (identical in all five languages)
acquired conn-1
acquired conn-2
no connection free
released conn-1
acquired conn-1

Use it when

  • Creation is expensive compared to use (connections, threads, GPU buffers).
  • You need to cap how many exist at once.
  • Objects can be reset to a clean state when returned.

Skip it when

  • Objects are cheap. Pooling adds locking and bugs for no gain.
  • Objects hold per-user state you cannot reset safely.

Where it shows up in LLD

  • Parking Lot: the parking spots themselves behave like a pool (find a free one, mark it busy, free it on exit).
  • Database connection pool, thread pool, rate limiter workers.
  • Elevator or taxi dispatch: a pool of cars to assign from.

Going deeper SDE-2 and SDE-3

  • Thread safety is the heart of it: acquire and release must be atomic. In practice use a blocking queue (Java BlockingQueue, Python queue.Queue, a Go buffered channel) so waiting callers block cleanly.
  • Always release in a finally block or with a context manager, or leaked objects slowly starve the pool.
  • Pick a policy for an empty pool: block with a timeout, throw, or create more up to a cap.
  • Reset state on release (clear the transaction, empty the buffer), or the next borrower inherits the last one's mess.
  • This is not a GoF pattern, but it comes up constantly in LLD rounds.

Common mistakes

  • Forgetting to release.
  • Handing out the same object twice because of a race.
  • Returning an object that is still in use.
Everyday extras

Dependency Injection

Hand a class the things it needs from outside instead of letting it create them itself.

Explain it like I am new

A chef who is given ingredients instead of growing them. The chef cooks the same way whether the tomatoes come from the market or from a test kitchen's shelf.

The problem

An OrderService that does new EmailNotifier() inside itself is welded to email. You cannot test it without sending real emails, and switching to SMS means editing the class.

The idea

Make the class depend on an interface (Notifier) and pass an implementation in, usually through the constructor. The class neither knows nor cares which one it got. Whoever builds the object (your main function or a DI container) chooses.

Dependency Injection class diagramOrderService-notifier: Notifier+confirm(id)<<interface>>Notifier+send(message)EmailNotifierFakeNotifierinjected
OrderService depends on the Notifier interface. The caller decides which one to plug in.

See it in code

The same OrderService sends through a real notifier in production and a fake one in tests.

Python · main.py

class EmailNotifier:
    def send(self, message): print("EMAIL:", message)


class FakeNotifier:  # used in tests: nothing is really sent
    def send(self, message): print("FAKE (test):", message)


class OrderService:
    def __init__(self, notifier):  # injected, not created here
        self.notifier = notifier

    def confirm(self, order_id):
        self.notifier.send(f"order {order_id} confirmed")


OrderService(EmailNotifier()).confirm(42)  # production wiring
OrderService(FakeNotifier()).confirm(42)   # test wiring

Java · Main.java

public class Main {
    public static void main(String[] args) {
        new OrderService(new EmailNotifier()).confirm(42); // production wiring
        new OrderService(new FakeNotifier()).confirm(42);  // test wiring
    }
}

interface Notifier { void send(String message); }

class EmailNotifier implements Notifier {
    public void send(String message) { System.out.println("EMAIL: " + message); }
}

class FakeNotifier implements Notifier { // used in tests: nothing is really sent
    public void send(String message) { System.out.println("FAKE (test): " + message); }
}

class OrderService {
    private final Notifier notifier;

    OrderService(Notifier notifier) { this.notifier = notifier; } // injected, not created here

    void confirm(int orderId) { notifier.send("order " + orderId + " confirmed"); }
}

C++ · main.cpp

#include <iostream>
#include <string>

struct Notifier {
    virtual ~Notifier() = default;
    virtual void send(const std::string& message) = 0;
};

struct EmailNotifier : Notifier {
    void send(const std::string& m) override { std::cout << "EMAIL: " << m << "\n"; }
};

struct FakeNotifier : Notifier {  // used in tests: nothing is really sent
    void send(const std::string& m) override { std::cout << "FAKE (test): " << m << "\n"; }
};

class OrderService {
public:
    explicit OrderService(Notifier& n) : notifier_(n) {}  // injected, not created here
    void confirm(int orderId) { notifier_.send("order " + std::to_string(orderId) + " confirmed"); }

private:
    Notifier& notifier_;
};

int main() {
    EmailNotifier email;
    FakeNotifier fake;
    OrderService(email).confirm(42);  // production wiring
    OrderService(fake).confirm(42);   // test wiring
}

JavaScript · main.js

class EmailNotifier { send(message) { console.log("EMAIL:", message); } }
class FakeNotifier { send(message) { console.log("FAKE (test):", message); } } // nothing is really sent

class OrderService {
  constructor(notifier) { this.notifier = notifier; } // injected, not created here
  confirm(orderId) { this.notifier.send(`order ${orderId} confirmed`); }
}

new OrderService(new EmailNotifier()).confirm(42); // production wiring
new OrderService(new FakeNotifier()).confirm(42);  // test wiring

Go · main.go

package main

import "fmt"

type Notifier interface{ Send(message string) }

type EmailNotifier struct{}
type FakeNotifier struct{} // used in tests: nothing is really sent

func (EmailNotifier) Send(m string) { fmt.Println("EMAIL:", m) }
func (FakeNotifier) Send(m string)  { fmt.Println("FAKE (test):", m) }

type OrderService struct{ notifier Notifier } // injected, not created here

func (s OrderService) Confirm(orderID int) {
	s.notifier.Send(fmt.Sprintf("order %d confirmed", orderID))
}

func main() {
	OrderService{EmailNotifier{}}.Confirm(42) // production wiring
	OrderService{FakeNotifier{}}.Confirm(42)  // test wiring
}
Output (identical in all five languages)
EMAIL: order 42 confirmed
FAKE (test): order 42 confirmed

Use it when

  • Almost always, for services that talk to databases, networks, clocks or other external things.
  • You want to test with fakes and mocks.
  • You want to switch implementations by configuration.

Skip it when

  • Tiny scripts, or simple value objects with no collaborators. Plain construction is fine.
  • You would pass a container or 'service locator' everywhere. That hides what each class needs, which is the opposite of the goal.

Where it shows up in LLD

  • Every LLD design. Payment, Notification, Repository and Strategy classes are all injected.
  • Interview tip: when you write new X() inside a class, ask yourself if it should be passed in instead.

Going deeper SDE-2 and SDE-3

  • This is the 'D' in SOLID: depend on abstractions, not concrete classes. Dependency Injection is the technique, Dependency Inversion is the principle, and an IoC container (Spring, Guice, .NET DI) is a tool that automates it.
  • Constructor injection (shown here) makes dependencies required and objects immutable. Setter injection allows optional ones but allows half-built objects.
  • Composition root: build the whole object graph in one place near the program start, and nowhere else.
  • DI is what makes Singleton and Strategy testable. A 'singleton' managed by a container can be replaced in tests.

Common mistakes

  • Passing a container everywhere (service locator), which hides dependencies.
  • Too many constructor parameters is a sign the class does too much.
Everyday extras

Null Object

Return a harmless do-nothing object instead of null, so callers never need to check for 'nothing'.

Explain it like I am new

An empty chair at a meeting instead of a missing chair. Everyone can still look at it, pass it a paper and move on, nothing breaks, and it just does nothing.

The problem

A lookup that can find no customer returns null, so every caller has to write if (customer != null). Forget one check and the program crashes with a null-pointer error.

The idea

Create a special class that implements the same interface as the real object but does the neutral thing: a guest with no discount, a logger that discards messages. The lookup returns it instead of null, and callers use it like any other object.

Null Object class diagram<<interface>>Customer+name()+discount(): intRealCustomerNullCustomername = guest, 0%
Both classes share an interface, so callers treat 'no customer' like any other customer.

See it in code

A customer lookup either finds Asha or returns a guest object. The greeting code has no null checks.

Python · main.py

class RealCustomer:
    def __init__(self, name, discount):
        self._name, self._discount = name, discount

    def name(self): return self._name
    def discount(self): return self._discount


class NullCustomer:  # does the neutral thing
    def name(self): return "guest"
    def discount(self): return 0


CUSTOMERS = {1: RealCustomer("Asha", 10)}


def find_customer(customer_id):
    return CUSTOMERS.get(customer_id, NullCustomer())  # never None


for customer_id in (1, 99):
    c = find_customer(customer_id)  # no null check needed below
    print(f"Hello, {c.name()}! Discount: {c.discount()}%")

Java · Main.java

import java.util.Map;

public class Main {
    static final Map<Integer, Customer> CUSTOMERS = Map.of(1, new RealCustomer("Asha", 10));

    static Customer findCustomer(int id) {
        return CUSTOMERS.getOrDefault(id, new NullCustomer()); // never null
    }

    public static void main(String[] args) {
        for (int id : new int[]{1, 99}) {
            Customer c = findCustomer(id); // no null check needed below
            System.out.println("Hello, " + c.name() + "! Discount: " + c.discount() + "%");
        }
    }
}

interface Customer {
    String name();
    int discount();
}

class RealCustomer implements Customer {
    private final String name;
    private final int discount;
    RealCustomer(String name, int discount) { this.name = name; this.discount = discount; }
    public String name() { return name; }
    public int discount() { return discount; }
}

class NullCustomer implements Customer { // does the neutral thing
    public String name() { return "guest"; }
    public int discount() { return 0; }
}

C++ · main.cpp

#include <iostream>
#include <map>
#include <memory>
#include <string>

struct Customer {
    virtual ~Customer() = default;
    virtual std::string name() const = 0;
    virtual int discount() const = 0;
};

struct RealCustomer : Customer {
    RealCustomer(std::string n, int d) : name_(std::move(n)), discount_(d) {}
    std::string name() const override { return name_; }
    int discount() const override { return discount_; }

private:
    std::string name_;
    int discount_;
};

struct NullCustomer : Customer {  // does the neutral thing
    std::string name() const override { return "guest"; }
    int discount() const override { return 0; }
};

std::unique_ptr<Customer> findCustomer(int id) {
    if (id == 1) return std::make_unique<RealCustomer>("Asha", 10);
    return std::make_unique<NullCustomer>();  // never a null pointer
}

int main() {
    for (int id : {1, 99}) {
        auto c = findCustomer(id);  // no null check needed below
        std::cout << "Hello, " << c->name() << "! Discount: " << c->discount() << "%\n";
    }
}

JavaScript · main.js

class RealCustomer {
  constructor(name, discount) { this._name = name; this._discount = discount; }
  name() { return this._name; }
  discount() { return this._discount; }
}

class NullCustomer { // does the neutral thing
  name() { return "guest"; }
  discount() { return 0; }
}

const CUSTOMERS = new Map([[1, new RealCustomer("Asha", 10)]]);
const findCustomer = (id) => CUSTOMERS.get(id) ?? new NullCustomer(); // never undefined

for (const id of [1, 99]) {
  const c = findCustomer(id); // no null check needed below
  console.log(`Hello, ${c.name()}! Discount: ${c.discount()}%`);
}

Go · main.go

package main

import "fmt"

type Customer interface {
	Name() string
	Discount() int
}

type RealCustomer struct {
	name     string
	discount int
}

func (c RealCustomer) Name() string  { return c.name }
func (c RealCustomer) Discount() int { return c.discount }

type NullCustomer struct{} // does the neutral thing

func (NullCustomer) Name() string  { return "guest" }
func (NullCustomer) Discount() int { return 0 }

var customers = map[int]Customer{1: RealCustomer{"Asha", 10}}

func findCustomer(id int) Customer {
	if c, ok := customers[id]; ok {
		return c
	}
	return NullCustomer{} // never nil
}

func main() {
	for _, id := range []int{1, 99} {
		c := findCustomer(id) // no nil check needed below
		fmt.Printf("Hello, %s! Discount: %d%%\n", c.Name(), c.Discount())
	}
}
Output (identical in all five languages)
Hello, Asha! Discount: 10%
Hello, guest! Discount: 0%

Use it when

  • Callers repeat null checks everywhere.
  • There is a sensible 'do nothing' or default behaviour (no discount, silent logger, empty list).
  • You want to remove branching from client code.

Skip it when

  • Absence is an error that must be noticed. Hiding it makes bugs silent. Throw or return an explicit Optional instead.
  • There is no sensible neutral behaviour.

Where it shows up in LLD

  • Parking Lot: a 'no spot available' ticket object.
  • Customer, Coupon or Discount lookup returning a 'no discount' object.
  • Default logger or empty notification channel.

Going deeper SDE-2 and SDE-3

  • Tony Hoare called null his 'billion dollar mistake'. Null Object, Optional/Maybe types, and empty collections are all ways to avoid it.
  • Null Object versus Optional: Optional makes the caller handle absence explicitly, Null Object hides absence behind neutral behaviour. Choose by whether absence should be visible.
  • Often implemented as a Singleton since it has no state.
  • Real examples: Java Collections.emptyList(), a no-op logger, a NullPointer safe Strategy that does nothing.

Common mistakes

  • Hiding real errors.
  • Callers who still need to know it is the null object (then you have not removed the check).

Patterns that look alike

Many patterns have almost the same class diagram. What differs is the intent: the problem each one solves. Interviewers love asking 'what is the difference between X and Y?', so here are the pairs and groups that cause the most confusion.

PatternsWhat they shareHow they differQuick test
Strategy vs State Both hand work to an interchangeable object. Strategy is picked from outside and normally stays put. State changes by itself as the object runs, and the states often know about each other. Does the object move to the next one on its own after events? State. Does the caller choose? Strategy.
Decorator vs Proxy vs Adapter vs Facade All four wrap another object. Decorator adds behaviour behind the same interface. Proxy controls access behind the same interface. Adapter converts to a different interface. Facade gives one simple interface over many classes. Same interface plus extra feature: Decorator. Same interface plus gatekeeping: Proxy. Different interface: Adapter. Many classes: Facade.
Factory Method vs Abstract Factory vs Builder All three create objects for you. Factory Method makes one product and lets subclasses choose which. Abstract Factory makes a whole matching family. Builder makes one complex product step by step. One product: Factory Method. A family that must match: Abstract Factory. Many options on one product: Builder.
Observer vs Mediator Both stop objects from knowing each other directly. Observer is one-to-many: a subject broadcasts and listeners decide. Mediator is many-to-many: a central object routes messages by rules. A change is announced to whoever cares: Observer. A coordinator decides who talks to whom: Mediator.
Template Method vs Strategy Both let part of an algorithm vary. Template Method uses inheritance and is fixed at compile time. Strategy uses composition and can change at runtime. Need to swap at runtime or avoid inheritance: Strategy. Fixed order of steps in a base class: Template Method.
Command vs Strategy Both turn behaviour into an object. A Command is one request: it can be stored, queued, logged and undone. A Strategy is a way of doing something that you plug in. Do you need to remember or undo the action? Command. Do you need to choose how to do it? Strategy.
Composite vs Decorator Both are recursive: an object holds objects of its own type. Composite holds many children and combines their results. Decorator holds exactly one and adds behaviour to it. A tree: Composite. A single wrapped object with extras: Decorator.
Memento vs Command vs Prototype All can help with undo and copying. Memento stores a snapshot of state. Command stores the operation (and how to reverse it). Prototype copies an object but is not about history. Restore a whole state: Memento. Reverse one action: Command. Make a new similar object: Prototype.
Object Pool vs Flyweight Both reuse objects to save resources. Pool objects are borrowed by one user at a time and returned. Flyweights are shared by everyone at the same moment and never change. Lent and returned: Object Pool. Shared and read-only: Flyweight.
Chain of Responsibility vs Decorator Both pass a call along a line of objects. A chain handler may stop the request. A decorator always calls the next one and adds its own behaviour. Can a step end the request early? Chain of Responsibility.

Which patterns for which LLD problem

These are the usual suspects. They are a starting point, not a rule: use a pattern only if it solves a problem in your design.

ProblemPatterns and where they fit
Parking Lot
Elevator System
  • State: idle, moving, doors open
  • Strategy: scheduling: nearest car, direction-based
  • Observer: floor displays and alerts
  • Command: floor and cabin button presses
Vending Machine
ATM
Library Management
Food Delivery
Ride Sharing
Chess / Tic-Tac-Toe
Text Editor
Notification System
Logger
File System / Google Drive
Splitwise / Expense Sharing
Movie Ticket Booking
Rate Limiter
LRU / LFU Cache

How to talk about patterns in an interview

Naming a pattern earns nothing on its own. Explaining why it fits does. Use this four-part sentence:

  1. The problem. 'Pricing rules will change, and I do not want a growing if/else in the exit method.'
  2. The pattern. 'So I will use Strategy: one PricingStrategy interface with a class per rule.'
  3. The benefit. 'Adding weekend pricing is a new class and nothing else changes.'
  4. The cost. 'It means a few more small classes, which is fine because pricing is the part most likely to change.'

Mistakes that cost points

  • Pattern-stuffing. Adding five patterns to a design that needed none. Simple is a strength.
  • Reciting the textbook. Explain it using the problem in front of you, not the book's example.
  • Starting with the pattern. Start with the requirements. Introduce a pattern only when you meet the problem it solves.
  • Ignoring concurrency. If two threads can reach your Singleton, pool or observer list, say how you keep it safe.
  • Silent trade-offs. Every pattern has a cost. Say it before the interviewer has to ask.

Frequently asked questions

Do I need to memorise all the design patterns for a low-level design interview?

No. A handful appear in almost every LLD round: Strategy, Observer, Factory, Singleton, State, Decorator and Command. Learn those well enough to write from scratch, and know the rest well enough to recognise them and say when they fit.

Which design patterns are asked most in LLD interviews?

Strategy, Observer, Factory Method, Singleton, State, Decorator and Command show up the most. Typical problems like Parking Lot, Elevator, Vending Machine and Notification System use two to four of them each.

What is the difference between low-level design and high-level design?

High-level design (HLD) decides which services, databases, caches and queues make up a system and how they scale. Low-level design (LLD) decides the classes, interfaces, methods and relationships inside one of those services. Design patterns belong to LLD.

Should I use a design pattern in every LLD answer?

No. Use a pattern when it removes a real problem, such as a growing if/else or tight coupling. Forcing patterns into a simple design is a common reason interviewers mark answers down. Saying 'a simple class is enough here' is often the strongest answer.

Are design patterns language specific?

No. They are ideas about how to arrange classes and objects. The examples here show the same pattern in Python, Java, C++, JavaScript and Go, and some languages need less code because of built-in features such as closures, iterators or pattern matching.

How do I practice design patterns?

Read the idea, run the code, then change it: add a new strategy, a new state or a new observer. Then take a classic LLD problem and list which patterns you would use and why before you write any code.

Pair LLD with high-level design

Patterns decide what is inside a service. System design decides how many services there are and how they scale. A complete interview needs both. Build and stress-test the high-level side in the PRISM simulator.