DEV Community

Cover image for The Only Design Pattern Cheat Sheet You'll Need Before Interviews
Prateek Prabhakar
Prateek Prabhakar

Posted on • Originally published at Medium

The Only Design Pattern Cheat Sheet You'll Need Before Interviews

You've probably read a lot about design patterns, most of them have long explanations, heavy UML diagrams, and abstract examples that are hard to connect with real life.
But let's be honest, when you're preparing for a tech interview, you don't need a textbook. You need a quick, crisp, memorable guide that tells you,

  • What the pattern is 
  • Why it exists 
  • A real world hook to remember it 
  • A tiny pseudo code snippet for recall 

That is exactly what this Design Pattern Cheat Sheet is.
Think of it as your one stop destination to revise all design patterns in minutes, with hooks and analogies that will stick in your head when interview pressure hits.
And if you want to go deeper, don't worry, I have already written detailed articles for each pattern. You'll find the links next to each one for a full deep dive.


Creational Patterns

Creational design patterns are like a set of blueprints or recipes for creating objects. They separate the process of HOW objects are created from the code that actually USES them. This makes our code more flexible and easier to change later on.

1.Factory Method

Factory Method Pattern: Analogy - The Hiring Manager

// Interface
Interface Sender
    Method Send(msg)

// Concrete products
Class EmailSender implements Sender
    Send(msg) → print "Email: " + msg

Class SmsSender implements Sender
    Send(msg) → print "SMS: " + msg

// Creator
Abstract Class NotificationCreator
    Abstract Method CreateSender()

Class EmailCreator extends NotificationCreator
    CreateSender() → new EmailSender()

Class SmsCreator extends NotificationCreator
    CreateSender() → new SmsSender()

// Caller
creator = new EmailCreator()
sender  = creator.CreateSender()
sender.Send("Hey! How are you doing?")
Enter fullscreen mode Exit fullscreen mode

2.Abstract Factory

Abstract Factory Pattern: Analogy - The Outfit Stylist

// Abstract Factory
Interface UIFactory
    Method CreateButton()
    Method CreateInput()

// Concrete factories
Class DarkFactory implements UIFactory
    CreateButton() → new DarkButton()
    CreateInput()  → new DarkInput()

Class LightFactory implements UIFactory
    CreateButton() → new LightButton()
    CreateInput()  → new LightInput()

// Caller
factory = new DarkFactory()
btn = factory.CreateButton()
inp = factory.CreateInput()
Enter fullscreen mode Exit fullscreen mode

3.Prototype

Prototype Pattern: Analogy - The Object Template

// Prototype interface
Interface Document
    Method Clone()

// Concrete prototype
Class Invoice implements Document
    Property header, footer
    Clone() → return shallowCopy(this)

// Caller
invoice1 = new Invoice("Logo A", "Thanks")
invoice2 = invoice1.Clone()
invoice2.footer = "Updated Footer"
Enter fullscreen mode Exit fullscreen mode

4.Singleton

Singleton Pattern: Analogy - The Uno Captain

// Singleton
Class Config
    Private static instance
    Private Constructor()

    Static Method GetInstance()
        If instance == null
            instance = new Config()
        return instance

// Caller
c1 = Config.GetInstance()
c2 = Config.GetInstance()
// c1 == c2
Enter fullscreen mode Exit fullscreen mode

5.Builder

Builder Pattern: Analogy - The Object Chef

Class Notification
    Props: Title, Message, IsEmail, IsSMS, IsPush, Priority

Class NotificationBuilder
    Constructor() -> this.n = new Notification()
    Method SetTitle(t)         -> n.Title = t; return this
    Method SetMessage(m)       -> n.Message = m; return this
    Method EnableEmail()       -> n.IsEmail = true; return this
    Method EnableSMS()         -> n.IsSMS   = true; return this
    Method EnablePush()        -> n.IsPush  = true; return this
    Method WithPriority(p)     -> n.Priority = p; return this
    Method Build()             -> return n

// Caller
notification = new NotificationBuilder()
                 .SetTitle("Big Sale!")
                 .SetMessage("50% off today")
                 .EnableEmail()
                 .EnablePush()
                 .WithPriority("High")
                 .Build()
Enter fullscreen mode Exit fullscreen mode

Structural Patterns

Structural design patterns are a set of rules for putting together classes and objects to create bigger, more useful systems. They are all about composition, which means combining objects instead of relying solely on inheritance. Think of it like building with LEGOs, you are fitting different pieces together to make a larger, more complex model.

6.Adapter

Adapter Pattern: Analogy - The Universal Adapter

// Old interface
Class LegacyPayment
    Method MakePayment(amount)

// Adapter
Class PaymentAdapter implements NewPayment
    legacy = new LegacyPayment()
    Pay(amount) → legacy.MakePayment(amount)

// Caller
p = new PaymentAdapter()
p.Pay(100)
Enter fullscreen mode Exit fullscreen mode

7.Decorator

Decorator Pattern: Analogy - The Coffee Customizer

// Base
Interface Coffee
    Method Cost()

Class SimpleCoffee implements Coffee
    Cost() → 50

// Decorator
Class MilkDecorator implements Coffee
    coffee
    Constructor(c) → coffee = c
    Cost() → coffee.Cost() + 20

// Caller
coffee = new MilkDecorator(new SimpleCoffee())
print coffee.Cost()   // 70
Enter fullscreen mode Exit fullscreen mode

8.Composite

Composite Pattern: Analogy - The File Tree Organizer

// Component
Interface FileSystemItem
    Display(indent)

// Leaf
Class File implements FileSystemItem
    Display(i) → print i + "File"

// Composite
Class Folder implements FileSystemItem
    items = []
    Add(item) → items.Add(item)
    Display(i)
        print i + "Folder"
        For item in items → item.Display(i+1)

// Caller
root = new Folder()
root.Add(new File())
root.Display(0)
Enter fullscreen mode Exit fullscreen mode

9.Facade

Facade Pattern: Analogy - The One Stop Counter

// Subsystems
Class Lights
    Method Dim()

Class TV
    Method TurnOn()

// Facade
Class HomeTheaterFacade
    Method StartMovieNight()
        Lights.Dim()
        TV.TurnOn()

// Caller
theater = new HomeTheaterFacade()
theater.StartMovieNight()
Enter fullscreen mode Exit fullscreen mode

10.Proxy

Proxy Pattern: Analogy - The Bodyguard

// Subject
Interface Service
    Request()

// Real subject
Class RealService implements Service
    Request() → print "Real work done"

// Proxy
Class ServiceProxy implements Service
    real = new RealService()
    Request()
        print "Proxy check..."
        real.Request()

// Caller
s = new ServiceProxy()
s.Request()
Enter fullscreen mode Exit fullscreen mode

11.Flyweight

Flyweight Pattern: Analogy - The Character Cache

// Flyweight
Class Character
    symbol
    Constructor(s) → symbol = s

// Factory
Class CharFactory
    cache = {}
    GetChar(s)
        If not in cache → cache[s] = new Character(s)
        return cache[s]

// Caller
c1 = factory.GetChar("A")
c2 = factory.GetChar("A")
// same instance
Enter fullscreen mode Exit fullscreen mode

12.Bridge

Bridge Pattern: Analogy - The Music Connector

// Implementor
Interface Device
    TurnOn()

Class TV implements Device
    TurnOn() → print "TV On"

// Abstraction
Class Remote
    device
    Constructor(d) → device = d
    Press() → device.TurnOn()

// Caller
r = new Remote(new TV())
r.Press()
Enter fullscreen mode Exit fullscreen mode

Behavioral Patterns

Behavioral design patterns are about defining how objects interact and communicate with each other. They focus on delegating responsibilities and ensuring objects can work together effectively without being tightly coupled. Think of them as the traffic rules for our code. They manage the flow of requests and the assignment of tasks between different objects.

13.Strategy

Strategy Pattern: Analogy - The Coupon Brain

// Strategy
Interface Coupon
    Apply(amount)

// Concrete strategies
Class Flat50 implements Coupon
    Apply(amount) → amount - 50

Class TenPercent implements Coupon
    Apply(amount) → amount * 0.9

// Caller
coupon = new Flat50()
print coupon.Apply(500)
Enter fullscreen mode Exit fullscreen mode

14.Observer

Observer Pattern: Analogy - The Youtube Subscriber

// Subject
Class Channel
    subs = []
    AddSub(s) → subs.Add(s)
    Upload(video)
        For s in subs → s.Notify(video)

// Observer
Class User
    Notify(v) → print "New video: " + v

// Caller
ch = new Channel()
usr = new User()
ch.AddSub(usr)
ch.Upload("Design Patterns")
Enter fullscreen mode Exit fullscreen mode

15.Command

Command Pattern: Analogy - The Remote Control

// Command
Interface Command
    Execute()

Class LightOn implements Command
    Execute() → print "Light ON"

// Invoker
Class Remote
    Set(cmd) → this.cmd = cmd
    Press() → cmd.Execute()

// Caller
remote = new Remote()
remote.Set(new LightOn())
remote.Press()
Enter fullscreen mode Exit fullscreen mode

16.Chain of Responsibility

Chain of Responsibility Pattern: Analogy - The Customer Support Escalation

// Handler
Abstract Class Handler
    next
    SetNext(h) → next = h
    Handle(req)
        If next != null → next.Handle(req)

// Concrete
Class Manager extends Handler
    Handle(req)
        If req < 1000 → print "Manager handled"
        Else super.Handle(req)

// Caller
mgr = new Manager()
dir = new Director()
mgr.SetNext(dir)
mgr.Handle(2000)
Enter fullscreen mode Exit fullscreen mode

17.State

State Pattern: Analogy - The Mood Manager

// State
Interface State
    Play()

Class HappyState implements State
    Play() → print "Party music"

Class SadState implements State
    Play() → print "Sad songs"

// Context
Class MusicPlayer
    state
    SetState(s) → state = s
    Play() → state.Play()

// Caller
mp = new MusicPlayer()
mp.SetState(new HappyState())
mp.Play()
Enter fullscreen mode Exit fullscreen mode

18.Mediator

Mediator Pattern: Analogy - The Air Traffic Controller

// Mediator
Class ChatRoom
    Send(msg, user) → print user + ": " + msg

// Colleague
Class User
    name, room
    Send(msg) → room.Send(msg, name)

// Caller
room = new ChatRoom()
u1 = new User("Alice", room)
u1.Send("Hello!")
Enter fullscreen mode Exit fullscreen mode

19.Momento

Momento Pattern: Analogy - The Game Save

// Memento
Class Snapshot
    state
    Constructor(s) → state = s

// Originator
Class Editor
    text
    Save() → new Snapshot(text)
    Restore(snap) → text = snap.state

// Caller
e = new Editor()
e.text = "v1"
snap = e.Save()
e.text = "v2"
e.Restore(snap)  // back to v1
Enter fullscreen mode Exit fullscreen mode

20.Template Method

Template Method Pattern: Analogy - The Cooking Recipe

// Abstract
Class Game
    Play()
        Init()
        Start()
        End()

// Concrete
Class Football extends Game
    Init() → print "Setup field"
    Start() → print "Kickoff"
    End()   → print "Game over"

// Caller
g = new Football()
g.Play()
Enter fullscreen mode Exit fullscreen mode

21.Visitor

Visitor Pattern: Analogy - The Tax Auditor

// Visitor
Interface Visitor
    Visit(Book)

// Element
Class Book
    Accept(v) → v.Visit(this)

// Concrete visitor
Class TaxVisitor implements Visitor
    Visit(b) → print "Taxing book"

// Caller
book = new Book()
visitor = new TaxVisitor()
book.Accept(visitor)
Enter fullscreen mode Exit fullscreen mode

22.Iterator

Iterator Pattern: Analogy - The Product Browser

// Iterator
Interface Iterator
    HasNext()
    Next()

Class ProductIterator implements Iterator
    list, index=0
    HasNext() → index < list.Length
    Next() → list[index++]

// Caller
it = new ProductIterator(products)
while it.HasNext()
    print it.Next()
Enter fullscreen mode Exit fullscreen mode

23.Interpreter

Interpreter Pattern: Analogy - The Rule Engine

Interface Expression
    Method Interpret(product): bool

Class CategoryExpression implements Expression
    Constructor(category)
    Method Interpret(product) -> product.Category == category

Class PriceExpression implements Expression
    Constructor(limit)
    Method Interpret(product) -> product.Price < limit

Class AndExpression implements Expression
    Constructor(left, right)
    Method Interpret(product) -> left.Interpret(product) 
                                      AND right.Interpret(product)

// Usage
rule = new AndExpression(
          new CategoryExpression("Electronics"),
          new PriceExpression(1000))

For each product in products
    If rule.Interpret(product)
        Print "Selected: " + product.Name
Enter fullscreen mode Exit fullscreen mode

Design patterns aren't about throwing jargon in interviews. They are about writing clean, extensible, and maintainable code.
This cheat sheet is meant to be your last minute revision buddy, something you can glance at before an interview and instantly recall the essence of each pattern.
Remember,

  • There is no need to memorize patterns, instead it is important to understand the problem each one solves.
  • Use the hooks and analogies here to explain patterns in a simple, story like way during interviews.
  • When coding, reach for patterns not because they are "fancy," but because they make your design clearer and future proof.

With this in your toolkit, I am sure you will walk into interviews not just knowing the names of the patterns, but with the confidence to explain and apply them in real world scenarios.

Happy coding, and may your designs always stay simple and scalable!

Top comments (0)