Summary of patterns

Creational

Pattern

Mnemonic

Summary

LLD Case / Question

How It Is Used in LLD

Abstract Factory

AFter Concrete Factory

Creates families of related or dependent objects without specifying their concrete classes.

Design a Multi-Database Connector System. The system needs to support connecting to MySQL, Postgres, and MongoDB interchangeably.

An Abstract Factory interface creates the family of related objects (Connection, Query, Transaction). Concrete factories (MySQLFactory, PostgresFactory) implement this to return concrete objects, ensuring the client works only with abstractions.

Builder

Builder Responsibility Construction

Separates the construction of a complex object from its representation, allowing the same construction process to create different representations.

Design a complex Report Generator. A report has many optional attributes (header, footer, content) and different formats (PDF, HTML).

The Builder defines the steps (buildHeader(), buildBody()). Concrete Builders (e.g., PdfReportBuilder) implement these steps to produce the final complex Report object in a fluent, step-by-step manner, managing required and optional parameters.

Factory Method

FM for Interface

Defines an interface for creating an object, but lets subclasses decide which class to instantiate.

Design a Notification Service that can send messages via Email, SMS, or Push Notification, decided at runtime.

A NotificationFactory class defines the createNotification() method. Subclasses (EmailFactory, SmsFactory) override this method to return the concrete product, deferring instantiation to subclasses while exposing a uniform creation interface.

Prototype

Prototype Clones New objects

Creates new objects by copying an existing object (the prototype) to avoid coupling the client to the product classes.

Design a Maze/Game Level Editor where complex, pre-configured game objects (e.g., a specific type of enemy) need to be duplicated rapidly.

A prototype object is cloned to create new instances. This is more efficient than re-initializing the object from scratch, especially when object creation is resource-intensive (e.g., loading assets or complex data).

Singleton

Single Instance Global Access

Ensures a class has only one instance and provides a global point of access to it.

Design a Configuration Manager for a distributed application. The configuration must be loaded once and accessed globally by all modules.

The ConfigurationManager class uses a private constructor and a static method to return its single instance. This prevents multiple instances, ensuring all modules read and potentially write to the same configuration data source.

Structural

Pattern

Mnemonic

Summary

LLD Case / Question

How It Is Used in LLD

Adapter

Adapter Makes Interfaces Compatible

Allows objects with incompatible interfaces to collaborate. Converts the interface of a class into another interface clients expect.

Integrate a new, incompatible Third-Party Logging Library into an existing system without modifying hundreds of existing client calls.

The Adapter object wraps the new logger and implements the legacy logging interface that the clients expect. This bridges the interface gap, allowing the old code to call the new functionality seamlessly.

Bridge

Bridge Divides Abstraction Implementation

Decouples an abstraction from its implementation so that the two can vary independently.

Design a Drawing Program that can draw different shapes (Circle, Square) on different Rendering Engines (OpenGL, DirectX).

The Shape (Abstraction) holds a reference to a Renderer (Implementation) object. This allows any shape to be combined with any renderer, letting you add new shapes or new rendering APIs independently.

Composite

Composite Treats Objects Uniformly

Composes objects into tree structures. Clients can treat individual objects and compositions of objects uniformly.

Design a File System Component. The component needs to represent both individual files and directories, and clients should operate on both uniformly (e.g., getSize()).

Both File (Leaf) and Directory (Composite) implement the same component interface. The Directory object manages children and recursively delegates operations, forming a self-similar tree structure.

Decorator

Decorator Adds Responsibilities Dynamically

Attaches additional responsibilities to an object dynamically. Provides a flexible alternative to subclassing.

Design a Data Stream Wrapper that needs to support various runtime features like compression, encryption, and logging, combinable in any order.

Each feature (e.g., CompressedStream, EncryptedStream) is a Decorator that wraps the original stream and adds its functionality. Decorators can be chained dynamically to create flexible feature combinations.

Facade

Facade Simplifies Complex Subsystems

Provides a unified, high-level interface to a set of interfaces in a subsystem, making it easier to use.

Design an API Gateway for a legacy service. The service has dozens of methods, but the mobile client needs a few simple, aggregated operations.

The APIGateway acts as a Facade, providing simple methods (getUserSummary()) that internally orchestrate and delegate calls to the complex, multiple classes of the legacy subsystem.

Flyweight

Flyweight Shares Large Amounts

Shares common state among multiple objects to reduce memory usage.

Design a Text Editor capable of displaying a document with millions of characters, where each character object is memory-intensive.

The Flyweight object stores the intrinsic state (e.g., the character code, font name) which is shared. The extrinsic state (e.g., character position) is passed in by the client (the document structure).

Proxy

Proxy Controls Access

Provides a surrogate or placeholder for another object to control access to it.

Design a Virtual Proxy for a high-resolution image viewer. Loading the image should be delayed until the user clicks on the thumbnail.

The ImageProxy acts as a surrogate for the real, expensive HiResImage. It implements the same interface but adds lazy loading logic to defer creation and loading of the real object until it is absolutely needed.

Behavioural

Pattern

Mnemonic

Summary

LLD Case / Question

How It Is Used in LLD

Chain of Responsibility

Chain Handles Requests Sequentially

Avoids coupling the sender of a request to its receiver by giving more than one object a chance to handle the request.

Design a Workflow Engine where a request must pass through a sequence of processors (Authentication Validation Authorization).

Each processor (e.g., AuthHandler, ValidationHandler) is a handler in the chain. If a handler cannot process the request, it passes it to the next handler. This provides flexible ordering and allows handlers to be added/removed dynamically.

Command

Command Encapsulates Action

Encapsulates a request as an object, allowing for parameterization of clients with different requests, queuing, and undoable operations.

Design an advanced Text Editor with full Undo/Redo functionality.

Each user action (e.g., InsertTextCommand, DeleteTextCommand) is encapsulated as an object. These objects are stored in a stack. To implement Undo, the system simply executes the undo() method of the last command on the stack.

Iterator

Iterator Accesses Collection Sequentially

Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Design a custom Data Structure (like a sparse array or a graph) and provide a standard way for client code to traverse its elements.

The Iterator interface (hasNext(), next()) is defined, and the data structure provides a method to get a concrete Iterator implementation. The client code uses the standard iterator interface, decoupled from the collection's internal complexity.

Mediator

Mediator Reduces Direct Coupling

Defines an object that encapsulates how a set of objects interact. Promotes loose coupling by keeping objects from referring to each other explicitly.

Design an Air Traffic Control (ATC) System. Planes should not communicate directly but must coordinate via the Tower.

The Tower acts as the Mediator. All Plane objects communicate with the Tower, which relays or coordinates the messages. This drastically reduces the number of direct dependencies between the planes (objects).

Memento

Memento Saves Internal State

Captures and externalizes an object's internal state without violating encapsulation, so the object can be restored to this state later.

Implement a Save-State/Checkpoint Feature in a complex application or game without exposing the internal state of the core object.

The Originator (the object whose state is saved) creates a Memento object containing its current state. The Caretaker (the saving mechanism) stores the Memento but cannot inspect its contents. The Originator can later restore its state from the Memento.

Observer

Observer Notifies Dependent Objects

Defines a one-to-many dependency between objects so that when one object (the subject) changes state, all its dependents (observers) are notified.

Design a Logging and Auditing System. When an order status changes, multiple modules (inventory, billing, notification service) need to be updated automatically.

The Order object is the Subject. The other modules are Observers. When the Order state changes, it notifies all subscribed observers via a standard update() method, completely decoupling the change from the update logic.

State

State Alters Behavior Based On state

Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

Design a Vending Machine or an Order Management System where the behavior changes significantly depending on the current state (e.g., Idle, Has Coin, Dispensing).

The Vending Machine class delegates its behavior to one of the State objects (e.g., IdleState, HasCoinState). When an event occurs (e.g., insertCoin()), the current state object handles it and manages the transition to a new state.

Strategy

Strategy Encapsulates Algorithms

Defines a family of algorithms, encapsulates each one, and makes them interchangeable.

Design a Checkout Flow with different discount and tax calculation rules (e.g., student discount, seasonal sale, state tax). The choice of rules should be swappable at runtime.

An IPriceStrategy interface is defined. Concrete strategies (e.g., StudentDiscountStrategy) encapsulate the different algorithms. The CheckoutContext holds a reference to the current strategy and can swap it easily to change the pricing logic.

Template Method

Template Defines Skeleton Steps

Defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure.

Design a framework for Report Generation where the core process is fixed (Fetch Data Process Format Print), but the Process and Format steps differ for different report types.

The abstract base class defines the overall Template Method (e.g., generateReport()) which calls abstract "hook" methods for the customizable steps. Subclasses implement these hooks to provide specific logic without altering the workflow structure.

Visitor

Visitor Adds Operations Without Modifying Elements

Represents an operation to be performed on the elements of an object structure. Lets you define a new operation without changing the classes of the elements.

Design a Compiler/Interpreter. You need to perform operations like type-checking, code generation, and optimization on an Abstract Syntax Tree (AST).

Each operation (e.g., TypeCheckVisitor, CodeGenerationVisitor) is a Visitor class that implements the visit() method for every element type in the AST. This allows you to add new operations without modifying the AST node classes themselves.

Code examples

Creational design patterns focus on the best ways to instantiate objects. They hide the creation logic rather than having you instantiate objects directly using the new operator. This gives the program more flexibility in deciding which objects need to be created for a given use case.

Here is the implementation of the five core creational patterns in Python.


1. Singleton Pattern

Intent: Ensures that a class has only one instance and provides a global point of access to it.

__new__ creates and returns the actual object instance (the "constructor"), while __init__ initializes that created object's attributes (the "initializer"); __new__ runs first, returning the object for __init__ to set up, but you usually only override __new__ for advanced cases like metaclasses or creating immutable types, rarely needing it for standard object setup.

Python


2. Factory Method Pattern

Intent: Defines an interface for creating an object but allows subclasses to alter the type of objects that will be created.

Python


3. Abstract Factory Pattern

Intent: Provides an interface for creating families of related or dependent objects without specifying their concrete classes.

Python


4. Builder Pattern

Intent: Separates the construction of a complex object from its representation, allowing the same construction process to create different representations.

Image of Builder design pattern diagramShutterstockPython


5. Prototype Pattern

Intent: Creates new objects by copying an existing object (the prototype) rather than creating from scratch.

Python


Summary Table

Pattern

Purpose

Use Case

Singleton

Limit to 1 instance

Database connections, Loggers.

Factory Method

Delegate creation to subclasses

Creating different types of documents.

Abstract Factory

Create families of objects

UI toolkits (Windows vs Mac buttons).

Builder

Step-by-step complex creation

Building a custom computer or Pizza.

Prototype

Clone existing objects

Large objects that are expensive to create.

Structural design patterns are all about how classes and objects are composed to form larger structures. They help ensure that if one part of a system changes, the entire structure doesn't need to be rebuilt.

Here is the implementation of the seven core structural patterns in Python.


1. Adapter Pattern

Intent: Allows objects with incompatible interfaces to collaborate. It acts as a wrapper that translates calls from one interface to another.

Python


2. Bridge Pattern

Intent: Splits a large class or a set of closely related classes into two separate hierarchiesβ€”abstraction and implementationβ€”which can be developed independently.

Python


3. Composite Pattern

Intent: Lets you compose objects into tree structures and then work with these structures as if they were individual objects. Great for "Part-Whole" hierarchies.

Python


4. Decorator Pattern

Intent: Lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors.

Python


5. Facade Pattern

Intent: Provides a simplified interface to a library, a framework, or any other complex set of classes.

Python


6. Flyweight Pattern

Intent: Lets you fit more objects into the available amount of RAM by sharing common parts of state between multiple objects instead of keeping all of the data in each object.

Python


7. Proxy Pattern

Intent: Provides a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request reaches the original object.

Python


Summary Table

Pattern

Focus

Real-World Analogy

Adapter

Compatibility

Travel power plug adapters.

Bridge

Independence

A remote control that works with any brand of TV.

Composite

Hierarchy

A folder containing files and other folders.

Decorator

Extension

Adding toppings to a pizza.

Facade

Simplicity

A "Start" button on a microwave that hides complex logic.

Flyweight

Efficiency

Using the same textures for 10,000 trees in a video game.

Proxy

Control

A credit card acting as a proxy for your bank account.

Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects. They describe not just patterns of objects or classes but also the patterns of communication between them.

Here is the implementation of the most common behavioral patterns in Python.


1. Chain of Responsibility

Intent: Passes requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.

Python


2. Command Pattern

Intent: Turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method arguments, delay or queue a request’s execution, and support undoable operations.

Python


3. Observer Pattern (Pub/Sub)

Intent: Lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing.

Python


4. Strategy Pattern1

Intent: Defines a family 2of algorithms, puts each of them into a separate class, and makes their objects interchangeable.

Python


5. State Pattern3

Intent: Lets an object alter its beh4avior when its internal state changes. It appears as if the object changed its class.

Python


6. Template Method Pattern

Intent: Defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure.

Python


7. Mediator Pattern

Intent: Reduces chaotic dependencies between objects. The pattern restricts direct communications between the objects and forces them to collaborate only via a mediator object.

Python


8. Memento Pattern

Intent: Lets you save and restore the previous state of an object without revealing the details of its implementation.

Python


Summary Table

Pattern

Use Case

Command

Undo/Redo operations, transactional logging, job queues.

Strategy

Switching sorting algorithms, different tax calculation methods.

Observer

Event handling systems, real-time dashboards (Pub/Sub).

State

Game state management (Menu -> Playing -> Game Over).

Mediator

Decoupling complex components (e.g., Air Traffic Control).

Memento

History tracking, "Save" points in applications.

Chain of Responsibility

Middleware, event bubbling, multi-stage validation.

Template Method

Standardizing a workflow with custom steps (e.g., CI/CD).


This is a very common problem β€” and the good news is:

you don’t need to memorize design patterns, you need to anchor them to problems your brain already understands.

It is perfectly normal to feel overwhelmed. There are 23 "classic" GoF (Gang of Four) patterns, and they often sound similar. The secret to remembering them isn't rote memorizationβ€”it's Visual Categorization and Problem-Pattern Mapping.

Here is a system to help you memorize them, followed by the interview probability ranking.


🧠 1. The "Memory Palace" Strategy

Instead of remembering names, remember the Purpose of the category.

  • Creational (Construction): How do I make the object? (Think of a Factory)

  • Structural (Assembly): How do I glue objects together? (Think of a Circuit Board)

  • Behavioral (Interaction): How do objects talk to each other? (Think of a Team of People)


πŸ† 2. Interview Probability Ranking (Top 12)

If you are short on time, focus on the "S-Tier" patterns. These cover 80% of LLD interview questions.

Pattern

Category

Probability

Common Interview Prompt

Strategy

Behavioral

🟒 Very High

"Design a Payment system with multiple methods."

Observer

Behavioral

🟒 Very High

"Design a Notification system or Stock Ticker."

Factory

Creational

🟒 Very High

"How would you create different types of UI buttons?"

Decorator

Structural

🟑 High

"Design a Pizza or Coffee shop with many toppings."

Singleton

Creational

🟑 High

"How do you ensure only one Database connection?"

State

Behavioral

🟑 High

"Design a Vending Machine or an ATM."

Builder

Creational

🟑 High

"How to create a complex 'User' object with 20 fields?"

Adapter

Structural

βšͺ Medium

"How to integrate a 3rd party API with a different format?"

Chain of Resp.

Behavioral

βšͺ Medium

"Design a Logger or a Middleware filter."

Facade

Structural

βšͺ Medium

"How do you simplify a complex internal library?"

Composite

Structural

πŸ”΄ Low

"Design a File System (Folders within Folders)."

Proxy

Structural

πŸ”΄ Low

"How to add caching or security before a DB call?"


πŸ’‘ 3. How to Remember: The "Trigger" Method

Associate each pattern with a single real-world object that triggers the memory.

Creational Patterns

  • Singleton: The Sun (There is only one).

  • Factory: A Pizza Store (You ask for a "Pepperoni" and it handles the dough/sauce).

  • Builder: LEGOs (You build a complex structure piece by piece).

  • Prototype: A Photocopy Machine (You copy an existing document).

Structural Patterns

  • Adapter: A Travel Plug (Converts US plug to EU socket).

  • Decorator: A Christmas Tree (You start with a tree and add ornaments/lights to it).

  • Facade: A Remote Control (One button handles the complex wiring of the TV/Audio).

  • Proxy: A Credit Card (It represents the money in your bank but adds a security layer).

Behavioral Patterns

  • Strategy: A GPS/Maps App (Choose "Walk," "Drive," or "Bike" β€” the route algorithm changes).

  • Observer: YouTube/Instagram (When a creator uploads, all subscribers get a notification).

  • State: A Traffic Light (Red, Yellow, Green β€” behavior changes based on color).

  • Command: A Restaurant Order (The waiter writes the order on a slip; it can be queued or canceled).


πŸ› οΈ 4. The "Cheat Sheet" for LLD Coding Rounds

When you get a problem, ask yourself these three questions to identify the pattern:

  1. "Does the object have a complex lifecycle or many states?" β†’ Use State Pattern.

  2. "Am I trying to support multiple algorithms/behaviors for one task?" β†’ Use Strategy Pattern.

  3. "Do I have multiple objects that need to stay in sync?" β†’ Use Observer Pattern.

  4. "Am I adding features to an object without changing its class?" β†’ Use Decorator Pattern.


Would you like me to take one of these "S-Tier" patterns (like Strategy or Observer) and show you how to write it in a professional, "Interview-Perfect" style?


Last updated