Skip to main content
InterviewHubPRO
HomeTracksSection 58: Design Patterns (GoF) (50 Qs)
Section 58 of 6450 Questions (1 Per Page)

Gang of Four (GoF) & Enterprise Software Design Patterns Master Interview Bank

Creational, Structural, Behavioral, and Architectural Design Patterns: Factory, Builder, Singleton, Adapter, Decorator, Facade, Proxy, Strategy, Observer, Command, Hexagonal, CQRS, and SAGA.

Curriculum Roadmap & Learning Path

3 Stages
Tip: Click any stage card above to instantly filter the question bank to that topic.3 Connected Milestones
50 of 50 Qs

Part 1: Creational & Structural Patterns (1 - 10)

10 Questions
1
Junior#design-patterns#Creational

What are the three Gang of Four (GoF) Pattern Categories?

Creational Patterns: Deal with object creation mechanisms, increasing flexibility and reuse of existing code (Factory, Builder, Singleton, Prototype) • Structural Patterns: Explain how to assemble objects and classes into larger structures while keeping them flexible and efficient (Adapter.

2
JuniorCode#design-patterns#Creational

What is the Singleton Pattern and how do you implement it thread-safely?

Ensures a class has only one instance and provides a global access point to it: Private constructor prevents direct instantiation • Static instance variable and public static getter • Double-Checked Locking (in Java / C#).

3
JuniorCode#design-patterns#Creational

What is the Factory Method Pattern?

Defines an interface for creating an object, but lets subclasses decide which class to instantiate: Decouples client code from concrete implementation classes.

4
JuniorCode#design-patterns#Creational

What is the Builder Pattern and when should you use it?

Separates the construction of a complex object from its representation, allowing the same construction process to create different representations: Use Case: Eliminates "Telescoping Constructors" where a class constructor has 10 parameters, most of which are optional.

5
JuniorCode#TypeScript

What is the Adapter Pattern and how does it reconcile incompatible interfaces?

Acts as a translator / wrapper between two incompatible interfaces: Analogy: A US-to-European power plug adapter • Example: Your legacy application expects an interface LegacyPaymentGateway.charge(cents), but a new third-party SDK provides.

6
JuniorCode#TypeScript

What is the Decorator Pattern and how does it differ from Inheritance?

Attaches new behaviors to objects dynamically at runtime by placing them inside special wrapper objects: Inheritance: Static (compile-time) and causes class explosion (e.g. EspressoWithMilk, EspressoWithMilkAndCaramel) • Decorator: You wrap a base object with multiple decorators dynamically.

7
Junior#design-patterns#Creational

What is the Facade Pattern and how does it simplify complex subsystems?

Provides a simple, unified, high-level interface to a complex library, framework, or set of classes: Analogy: A customer service representative who handles your order, billing, and shipping behind the scenes • Instead of client code orchestrating 10 classes (AudioCodec, VideoBuffer, HardwareDecoder, ColorCorrection), you provide a simple.

8
Junior#design-patterns#Creational

What is the Proxy Pattern and what are its common types (Virtual, Protection, Remote)?

Provides a surrogate or placeholder object that controls access to the real object: Virtual Proxy (Lazy Loading): Defers the creation of an expensive object (e.g. a 50 MB high-resolution image) until it is actually requested.

9
JuniorCode#design-patterns#Creational

What is the Strategy Pattern and how does it eliminate `if/else` ladders?

Defines a family of interchangeable algorithms, encapsulates each one, and makes them interchangeable at runtime: Context: Holds a reference to a Strategy interface • Client passes the desired strategy dynamically.

10
JuniorCode#design-patterns#Creational

What is the Observer Pattern and how does it implement Pub/Sub?

Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically: Subject: Maintains a list of observers; provides subscribe() and unsubscribe() • Observer: Defines an update() method called by the Subject.

Part 2: Behavioral Patterns & Communication (11 - 24)

14 Questions
11
JuniorCode#Behavioral

What is the Command Pattern and how does it enable Undo / Redo?

Encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support reversible operations: Every command object implements execute() and undo() • An Invoker maintains a history stack • Running a command: Calls cmd.execute() and pushes to stack.

12
Junior#Behavioral

What is the State Pattern and how does it differ from the Strategy Pattern?

Allows an object to alter its behavior when its internal state changes, appearing as if the object changed its class: Strategy vs State • Strategy: Client explicitly chooses which algorithm strategy to inject; strategies rarely know about other strategies.

13
JuniorCode#Components#Behavioral

What is the Template Method Pattern?

Defines the skeleton of an algorithm in an abstract base class, deferring some steps to subclasses without changing the algorithm's overall structure: Uses invariant steps and abstract hooks.

14
Junior#Behavioral

What is the Chain of Responsibility Pattern?

Passes a request along a dynamic 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 • The standard pattern behind HTTP Middleware pipelines (Express, Koa, ASP.NET Core) and authentication filters.

15
SeniorCode#System Design#Behavioral

What is Clean Architecture (The Onion / Hexagonal Architecture)?

Introduced by Uncle Bob to create systems independent of frameworks, databases, and UI: Dependency Rule: Dependencies always point inwards toward the core domain! • Entities (Core Domain): Pure business rules and models (Zero external dependencies) • Use Cases (Application Business Rules): Orchestrates data flow to/from entities.

16
Senior#System Design#Behavioral

What is Hexagonal Architecture (Ports and Adapters)?

Created by Alistair Cockburn: The core application resides inside a hexagon, isolated from the outside world • Ports: Inward-facing application interfaces (e.g. OrderRepositoryPort, PaymentProcessorPort) • Adapters: Outward-facing concrete implementations that plug into ports.

17
Junior#Behavioral

What is the Repository Pattern and what are its benefits?

Mediates between the domain and data mapping layers, acting like an in-memory collection of domain objects: Encapsulates database query logic (SELECT, INSERT) behind a collection-like interface (findById, save, delete) • Decouples domain logic from ORMs (Prisma, TypeORM, Hibernate) and SQL dialects.

18
Junior#Behavioral

What is the Unit of Work Pattern?

Instead of saving every entity modification to the database immediately (incurring 10 separate SQL round-trips) • The Unit of Work tracks all dirty, new, and deleted objects in memory, and commits them inside a single atomic database transaction upon completion.

19
JuniorCode#Behavioral

What is the CQRS (Command Query Responsibility Segregation) Pattern?

Segregates the data model for write operations (Commands) from the data model for read operations (Queries): Command Model: Optimized strictly for validating business rules, transactions, and maintaining invariants (writes to normalized relational DB).

20
Junior#Behavioral

What is the Event Sourcing Pattern?

Instead of storing only the current state of an entity, Event Sourcing stores the entire append-only sequence of immutable domain events that led to that state: Bank Account Balance is not stored as 500 • Instead, the database stores • AccountCreated (+0) • MoneyDeposited (+$1000).

21
JuniorCode#Behavioral

What is the Outbox Pattern and how does it guarantee Dual-Write consistency?

When an app must update a database AND publish an event to a message broker (Kafka/RabbitMQ): The Dual-Write Problem: If the database commit succeeds but the network fails before publishing to Kafka, data is out-of-sync! • Transactional Outbox Pattern.

22
Senior#State Management#System Design

What is the SAGA Pattern for Distributed Transactions?

Replaces slow 2-Phase Commit (2PC) across microservices with a sequence of local transactions: Each service executes a local transaction and publishes an event that triggers the next service's transaction.

23
Senior#System Design#Behavioral

What is the Circuit Breaker Pattern in distributed systems?

Prevents cascading failures when a downstream microservice is down: Closed State: Normal operation; requests pass through • Open State: When failure rate exceeds a threshold (e.g. 50% timeouts), the circuit opens immediately • Half-Open State: After a timeout, sends a single test probe request.

24
Junior#Behavioral

What is the Bulkhead Pattern?

Inspired by nautical ship bulkheads that compartmentalize hulls so a leak in one compartment doesn't sink the entire ship: Isolates critical resources into independent pools (thread pools, connection pools, CPU allocations) • Example: Allocate 30 threads for standard customer checkout, and 5 threads for third-party analytics.

Part 3: Architectural Patterns & Enterprise Systems (25 - 35)

26 Questions
25
Junior#design-patterns#Architectural Patterns

What is the Anti-Corruption Layer (ACL) in Domain-Driven Design?

A translation layer placed between a modern domain model and a legacy system or third-party service: Translates legacy data models and terminology into clean domain objects before they enter your domain core • Prevents legacy system bad practices and archaic concepts from "corrupting" your modern domain design.

26
Junior#design-patterns#Architectural Patterns

What is the difference between Anemic Domain Model and Rich Domain Model?

Anemic Domain Model (Anti-Pattern): Entities are purely dumb data holders with public getters/setters (class Order { public items, status; }) • Rich Domain Model (Best Practice): Entities encapsulate both data and the business logic that operates on that data (order.cancel(), order.addItem()).

27
Junior#design-patterns#Architectural Patterns

What is the Strangler Fig Pattern for monolithic migration?

A pattern to incrementally migrate a legacy monolithic application to microservices without a risky "Big Bang" rewrite: Place an API Gateway in front of the monolith • Implement new features or carve out individual capabilities (e.g. Authentication) as new microservices.

28
Senior#System Design

What is the Sidecar Pattern in Cloud-Native architectures?

Deploys components of an application into a separate process or container to provide supporting features without modifying the primary application code: Common examples in Kubernetes Pods • Envoy Proxy sidecar (Service Mesh for mTLS, traffic routing, metrics) • Fluentd / Datadog sidecar (Log harvesting).

29
Mid#design-patterns#Architectural Patterns

When does Design Pattern Over-Engineering harm software projects?

Applying GoF patterns blindly where simple procedural code is sufficient ("Patternitis"): Introducing 5 layers of Factories, Builders, and Adapters for a CRUD service that will only ever query a single PostgreSQL table • Increases cognitive load, makes debugging painful, and inflates codebase size.

30
Junior#design-patterns#Architectural Patterns

What is the Abstract Factory Pattern and how does it differ from Factory Method?

Factory Method: Uses inheritance to delegate creation of a single product to subclasses • Abstract Factory: Uses object composition to create families of related or dependent products (e.g., MacButton + MacCheckbox vs WinButton +.

31
Most AskedJunior#Prototypes

What is the Prototype Pattern and when should you use Cloning over constructors?

The Prototype Pattern creates new objects by copying (cloning) an existing instance rather than constructing from scratch.: Use Case: When object creation is computationally expensive (e.g. database loading, network lookups, complex calculations).

32
Junior#Forms#Data Structures

What is the Composite Pattern and how does it treat trees of objects uniformly?

The Composite Pattern organizes objects into tree structures to represent part-whole hierarchies. Clients treat individual leaf objects (e.g., File) and composite containers (e.g., Directory) through a single unified interface.

33
Junior#design-patterns#Architectural Patterns

What is the Bridge Pattern and how does it prevent a Cartesian explosion of subclasses?

The Bridge Pattern decouples an abstraction from its implementation so that both can vary independently. Instead of multiplying classes (M views \times N platforms = M \times N classes), the abstraction holds a reference to an implementation interface (M + N classes).

34
Junior#design-patterns#Architectural Patterns

What is the Flyweight Pattern and how does it minimize memory by sharing intrinsic state?

The Flyweight Pattern shares common, immutable data (Intrinsic State) across millions of objects rather than duplicating it in every instance. Mutable, context-specific data (Extrinsic State) is passed in dynamically.

35
Junior#design-patterns#Architectural Patterns

What is the Visitor Pattern and how does it add new operations without modifying existing classes?

The Visitor Pattern uses Double Dispatch (element.accept(visitor) -> visitor.visit(element)) to separate an algorithm from the object structure on which it operates, allowing new operations to be added without modifying the element classes.

36
Mid#Pipes#CI/CD & DevOps

Chain of Responsibility Pattern: Middleware pipelines and event bubbling.

Avoids coupling the sender of a request to its receiver by giving multiple objects a chance to handle the request: Handlers are chained together sequentially • Real-World Examples.

37
Mid#Behavioral

State Pattern vs Strategy Pattern: Structural similarities and behavioral differences.

Both patterns look structurally identical (a Context class delegating to an interface): Strategy Pattern: The client configures the Context with a specific algorithm (e.g. FastRouteStrategy vs ScenicRouteStrategy).

38
Mid#design-patterns#Architectural Patterns

Mediator Pattern: Decoupling communication dependencies into a central hub.

When dozens of components communicate directly with each other, they form a chaotic O(N^2) web of tight coupling: Mediator Pattern: Components (Colleagues) communicate strictly through a central Mediator object • Real-World Example.

39
Senior#design-patterns#Architectural Patterns

Memento Pattern: Snapshotting internal state for undo/redo workflows.

Captures and externalizes an object's internal state so the object can be restored to this state later, without violating encapsulation: Originator: The business object (e.g. Text Editor canvas) • Memento: Immutable state snapshot container.

40
Mid#design-patterns#Architectural Patterns

Interpreter Pattern: Building Domain-Specific Languages (DSLs) and rule engines.

Given a language, defines a representation for its grammar along with an interpreter that evaluates sentences in the language: Represents grammar rules as an Abstract Syntax Tree (AST) composed of Terminal Expressions (literal numbers, variable names) and Non-Terminal.

41
Most AskedMidCode#Dependency Injection

Service Locator Anti-Pattern vs Dependency Injection.

Service Locator: A central registry object that classes query to fetch dependencies.

42
Senior#State Management#System Design

Saga Pattern (Choreography vs Orchestration): Distributed transactions.

In a microservices architecture, you cannot use distributed ACID database locks (2PC) across services without catastrophic latency. A Saga is a sequence of local transactions: If Step 3 (Payment) fails, the Saga executes Compensating Transactions in reverse order (e.g. cancel reserved inventory, cancel pending order).

43
Mid#design-patterns#Architectural Patterns

Strangler Fig Pattern: Incrementally modernizing legacy monolithic systems.

Named after strangler fig trees that grow around host trees and gradually replace them: Instead of attempting a high-risk "Big Bang" rewrite of a 10-year-old monolith • Place an API Gateway / Reverse Proxy in front of the monolith • Implement new features or extract single domains (e.g. /billing) as modern microservices.

44
Mid#design-patterns#Architectural Patterns

Bulkhead Pattern: Isolating critical resources to prevent total system collapse.

Derived from naval ship hulls that divide the ship into watertight compartments (bulkheads): if water leaks into one section, the ship stays afloat: In software, partition resources (thread pools, connection pools, memory) • Dedicate 50 threads to the core Checkout service • Dedicate 10 threads to the third-party Recommendation service.

45
Mid#CLI

Ambassador Pattern: Offloading client-side connectivity to a local proxy.

Deploys a helper service alongside a client application (typically as a localhost process or Kubernetes sidecar): The application connects to localhost:8080 using standard plaintext HTTP • The Ambassador Proxy handles • Routing to remote cloud services • mTLS certificate encryption.

46
Senior#System Design

Sharding / Partitioning Pattern: Horizontal data scaling.

When a single database server hits physical CPU or disk capacity limits: Split the dataset horizontally across multiple distinct database servers (Shards) • Range-Based Sharding: Shard 1 holds IDs 1 - 1,000,000; Shard 2 holds 1,000,001 - 2,000,000 • Hash-Based Sharding: hash(customerid) % numshards.

47
Mid#design-patterns#Architectural Patterns

Gateway Aggregation / Backend-for-Frontend (BFF) Pattern.

Gateway Aggregation: An API Gateway aggregates multiple backend microservice calls into a single HTTP round-trip, saving cellular network • Backend-for-Frontend (BFF): Instead of a single monolithic API Gateway serving all clients, create dedicated gateway layers tailored to specific.

48
Mid#design-patterns#Architectural Patterns

Competing Consumers Pattern: Scalable concurrent message processing.

When the message production rate exceeds the processing capacity of a single consumer: Multiple identical consumer instances attach to a single shared message queue (RabbitMQ queue, AWS SQS) • The message broker dispenses each message to strictly one consumer in the pool.

49
Mid#design-patterns#Architectural Patterns

Claim Check Pattern: Handling large message payloads in event-driven systems.

Message brokers (Kafka, RabbitMQ, SQS) are designed for small payloads (< 256 KB); sending 50MB PDF files or 4K videos directly through message queues degrades broker memory and throughput: Claim Check Workflow • Producer uploads the 50MB file directly to cloud object storage (AWS S3 / GCS).

50
Mid#design-patterns#Architectural Patterns

Architectural Anti-Patterns: Golden Hammer, Lava Flow, and Big Ball of Mud.

Recognizing toxic architectural anti-patterns: Golden Hammer: Assuming a single favorite technology (e.g. Microservices, GraphQL, or MongoDB) is the universal solution for every single problem.