Reference

Interview Patterns

Tier 1โ€“3 pattern ranking โ€” what interviewers actually test and how to prepare.

01
Tier One ยท Must Know

Tier 1 โ€” Asked in Every Interview

These five patterns appear in virtually every system-design and coding interview. If you learn nothing else, learn these — interviewers assume you know them cold.

Pattern Category Why Interviewers Ask It What They’re Testing
Observer Behavioral Tests pub/sub, event-driven thinking, loose coupling Can you design a notification system where adding a new subscriber requires zero changes to the publisher? Do you understand the difference between push and pull models?
Strategy Behavioral Tests OCP, runtime polymorphism, replacing conditionals Given a growing if/else chain (payment methods, sorting algorithms, discount rules), can you extract each branch into a Strategy and swap at runtime?
Decorator Structural Tests composition over inheritance, wrapper chains Can you add behaviour (logging, caching, compression) to an object without subclassing? Can you explain how BufferedReader(new FileReader(f)) works?
Factory Method Creational Tests abstraction, dependency inversion Can you decouple object creation from usage? Do you know the difference between Factory Method, Abstract Factory, and a static factory?
Singleton Creational Tests thread safety, lazy init, tradeoffs Can you implement a thread-safe Singleton? Do you know why double-checked locking needs volatile? Can you explain when Singleton is an anti-pattern and when DI is better?
Quick Interview Tips per Pattern
Observer
  • Draw: Subject with subscribe(), unsubscribe(), notifyAll() + Observer with update()
  • Prove OCP: Adding a new observer type = zero edits to the subject
  • JDK example: java.beans.PropertyChangeListener
  • Downsides to mention: Memory leaks (forgotten subscribers), ordering issues
Strategy
  • Opening move: Show the ugly if/else version first, then refactor
  • Draw: PaymentStrategy interface → CreditCard, PayPal implementations → Context accepts strategy via constructor
  • JDK example: java.util.Comparator
  • Key phrase: “Encapsulate what varies”
Decorator
  • Show the chain: new Encryption(new Compression(new FileDataSource()))
  • Key rule: Each wrapper implements the same interface and delegates to the wrapped object
  • vs. Proxy: Decorator adds features; Proxy controls access
  • JDK example: java.io.BufferedReader(Reader)
Factory Method
  • Draw: Two parallel hierarchies — creators and products
  • Show: Abstract creator calls createProduct() inside a template method
  • Prove OCP: New product = one new creator subclass + one new product class, zero edits
  • Don’t confuse with: Abstract Factory (families) or static factory (no inheritance)
Singleton
  • Show: private constructor + static getInstance() + volatile field for double-checked locking
  • Downsides to mention: Hidden dependencies, hard to test, shared mutable state
  • Modern alternative: DI frameworks (@Singleton in Spring/Guice)
  • Bonus: Explain why volatile is needed (instruction reordering)
Tier 1 โ€” Where each pattern fits in a typical system
Your Service Factory Method creates objects Singleton shared instance Strategy swaps algorithm Observer notifies Decorator wraps behaviour
Interview prep order: Start with Strategy (easiest to explain with the if/else refactor story), then Observer, then Factory Method, then Decorator, then Singleton (deceptively hard — thread safety questions go deep).
02
Tier Two ยท Frequently Asked

Tier 2 โ€” Common at Mid-Senior Level

Tier 2 patterns appear regularly in mid-level and senior interviews. They test deeper design thinking — undo systems, fluent APIs, recursive structures, and legacy integration. You won’t be asked these in every interview, but not knowing them at a senior level is a red flag.

Pattern Category Why Interviewers Ask It What They’re Testing
Command Behavioral Tests undo/redo design, queue-based systems Can you model a request as an object? Design a text editor with undo. Show how commands can be queued, logged, and replayed.
Builder Creational Tests fluent API design, telescoping constructor problem Given a class with 10 optional parameters, how do you avoid a constructor with 10 args? Show a fluent .withX().withY().build() API. Mention StringBuilder as a JDK example.
Adapter Structural Tests legacy integration, interface mismatch You have a new analytics interface but a legacy reporting library with an incompatible API. Wrap it. Show both class adapter (inheritance) and object adapter (composition). JDK: Arrays.asList().
Composite Structural Tests recursive tree structures Model a file system where both files and directories implement the same interface. A directory contains children (files or other directories). Show getSize() recursing down the tree.
Template Method Behavioral Tests inheritance vs composition tradeoff Define an algorithm skeleton in a base class; let subclasses fill in specific steps. Show the hook method pattern. Then explain why Strategy (composition) is often preferred in modern code.
Quick Interview Tips per Pattern
Command
  • Draw 4 participants: Command interface (execute(), undo()), ConcreteCommand (e.g. BoldCommand), Receiver (the document), Invoker (toolbar/menu)
  • Show undo: Stack of commands → pop last → call undo()
  • JDK examples: Runnable, Callable
  • Bonus: Mention macro recording (replay a list of commands)
Builder
  • Opening move: Show the telescoping constructor: new Pizza(size, cheese, pepperoni, mushrooms, olives, sauce)
  • Refactor to: new PizzaBuilder().size("L").cheese(true).build()
  • Key benefit: Builder can enforce required vs. optional fields
  • vs. Abstract Factory: Builder constructs step-by-step; AF creates families at once
Adapter
  • One-liner: “Round peg, square hole — the Adapter wraps it to fit”
  • Two flavours: Class adapter (inheritance) vs. Object adapter (composition — preferred in Java)
  • Show composition: class StripeAdapter implements PaymentGateway { private StripeSdk sdk; }
  • JDK example: Arrays.asList()
Composite
  • Key idea: Shared Component interface with methods like getSize()
  • Leaf (File) returns its own size; Composite (Directory) iterates children, summing theirs
  • What interviewer wants: Treat individual objects and groups uniformly
  • JDK example: java.awt.Container
Template Method
  • Show: Abstract DataMiner with final mine() calling openFile()extractData()parseData()closeFile()
  • Subclasses override: Only the extract/parse steps
  • Modern alternative: Pass varying steps as Strategy objects (lambdas) to avoid rigid inheritance
  • JDK example: AbstractList
Tier 2 Relationship Map
How Tier 2 patterns relate to each other and to Tier 1
TIER 2 Command Builder Adapter Composite Template Method confused with both create wraps products both recursive alternative → prefer Strategy in modern code TIER 1 (related) Strategy Factory Method Factory Method Decorator ■ Gold = Tier 2 pattern □ Green dashed = Tier 1 pattern (related) - - - = commonly confused / related
Senior interview strategy: Tier 2 patterns are rarely asked in isolation. Interviewers combine them:
  • “Design a text editor”Command (undo/redo) + Memento (state snapshots)
  • “Design a plugin system”Factory Method + Adapter (wrapping third-party code)
  • “Design a notification service”Observer + Strategy (channel routing)
  • “Design a file system”Composite + Iterator + Visitor

Practice pattern combinations, not just individual patterns.

03
Tier Three ยท Deep Dives

Tier 3 โ€” Senior / Architecture Rounds

Tier 3 patterns surface in senior and staff-level architecture rounds. They test whether you can model complex state machines, optimize memory at scale, decouple deeply nested systems, and traverse structures without coupling to their internals. Knowing these signals depth beyond the standard playbook.

Pattern Category Why Interviewers Ask It What They’re Testing
Proxy Structural Tests lazy loading, access control, caching Can you design a virtual proxy that defers expensive initialization? Do you understand how Spring AOP @Transactional works under the hood?
State Behavioral Tests FSM modelling, replacing nested conditionals Given an order lifecycle (Pending → Paid → Shipped → Delivered → Cancelled), can you model each state as a class that handles its own transitions instead of one giant switch?
Mediator Behavioral Tests decoupling in UI/event systems Can you design a chat room or air-traffic control system where participants communicate through a central hub instead of direct references? Do you know when Mediator becomes a God Object?
Prototype Creational Tests cloning, avoiding expensive construction Can you implement deep clone vs. shallow clone? When is cloning preferable to calling a constructor? Do you know the pitfalls of Object.clone() in Java?
Bridge Structural Tests separating abstraction from implementation Given Shape × Renderer (Circle, Square × SVG, Canvas, PDF), can you avoid a class explosion by splitting into two independent hierarchies connected by composition?
Flyweight Structural Tests memory optimization at scale A text editor renders 100,000 characters โ€” how do you avoid 100,000 font/style objects? Can you separate intrinsic (shared) from extrinsic (per-instance) state?
Chain of Responsibility Behavioral Tests middleware pipelines, request routing Can you design an HTTP middleware stack or a support ticket escalation system where each handler decides to process or pass along?
Visitor Behavioral Tests adding operations to closed class hierarchies Given an AST or a tax calculation system, can you add new operations (print, validate, serialize) without modifying the node classes? Do you understand double dispatch?
Quick Interview Tips per Pattern
Proxy
  • Three variants: Virtual (lazy load), Protection (access control), Remote (network stub)
  • vs. Decorator: Proxy controls access; Decorator adds behaviour. Proxy often creates the real object itself.
  • JDK example: java.lang.reflect.Proxy, Spring AOP proxies
  • Key question: “Who controls the object’s lifecycle?” — if the wrapper does, it’s a Proxy
State
  • Draw: Context holds a State reference; each ConcreteState handles actions and triggers transitions
  • vs. Strategy: Both swap behaviour — Strategy swaps from outside; State transitions from inside
  • Classic scenario: Vending machine (Idle → HasCoin → Dispensing → OutOfStock)
  • JDK example: java.util.Iterator (internal state drives hasNext()/next())
Mediator
  • One-liner: Air traffic control — planes don’t talk to each other, they talk to the tower
  • Draw: Colleagues register with Mediator; all communication routes through it
  • Danger: Mediator can become a God Object — keep it thin, delegate logic back to colleagues
  • JDK example: java.util.concurrent.Executor, javax.swing.ButtonGroup
Prototype
  • When to use: Object construction is expensive (DB queries, file I/O) but cloning is cheap
  • Deep vs. shallow: Shallow copies references; deep copies the entire object graph
  • Java pitfall: Object.clone() is shallow by default and requires Cloneable marker — prefer copy constructors
  • JDK example: Object.clone(), ArrayList copy constructor
Bridge
  • Problem it solves: M × N class explosion (e.g. 3 shapes × 3 renderers = 9 classes without Bridge, 6 with it)
  • Draw: Abstraction hierarchy (Shape) holds a reference to Implementation hierarchy (Renderer)
  • vs. Adapter: Adapter makes incompatible things work together after the fact; Bridge is designed upfront to allow independent variation
  • JDK example: java.util.logging (Logger + Handler)
Flyweight
  • Key split: Intrinsic state (shared, immutable) vs. Extrinsic state (per-context, passed in)
  • Classic scenario: Text editor — character glyphs share font/style objects; position is extrinsic
  • Implementation: Factory + cache (pool) — return existing object if already created
  • JDK example: Integer.valueOf() (caches -128..127), String.intern()
Chain of Responsibility
  • Draw: Linked list of handlers, each with handle(request) and a next reference
  • Each handler: Either processes the request OR passes it to the next handler
  • Real-world: HTTP middleware (auth → logging → rate-limit → controller)
  • JDK example: javax.servlet.Filter, java.util.logging.Logger
Visitor
  • Key mechanism: Double dispatch — element calls visitor.visit(this), routing to the correct overload
  • When to use: Class hierarchy is stable but operations change frequently
  • Tradeoff: Adding a new element type requires editing every visitor (hard to extend structure, easy to extend operations)
  • JDK example: java.nio.file.FileVisitor, javax.lang.model.element.AnnotationValueVisitor
Tier 3 โ€” Problem domains each pattern addresses
Access & Lifecycle State & Communication Structure & Traversal Proxy lazy load, access control Prototype clone vs. construct Flyweight memory optimization State FSM, replace nested conditionals Mediator decouple N:N communication Chain of Responsibility pipeline / middleware Bridge avoid M×N explosion Visitor add ops without modifying classes ■ Gold = Creational / Structural ■ Green = Behavioral (communication) ■ Blue = Structural (traversal)
Architecture round strategy: Tier 3 patterns are about tradeoffs, not just implementation:
  • Proxy vs. Decorator: Both wrap — explain when you’d pick one over the other
  • State vs. Strategy: Both swap behaviour — explain the direction of control
  • Visitor tradeoff: Easy to add operations, hard to add new element types — when is this acceptable?
  • Flyweight + Proxy combo: Load heavy objects on demand (Proxy) and share their immutable parts (Flyweight)

At this level, interviewers care more about your reasoning than your UML diagram.