Design patterns are named, reusable solutions to recurring problems in structuring object-oriented code, usually studied alongside the SOLID principles. This section groups questions into creational, structural and behavioral patterns, including Strategy, Builder, Factory, Singleton, Observer, Decorator and Adapter, plus OOP fundamentals and refactoring scenarios drawn from everyday code.
All 37 Design Patterns quiz questions below come with a short explanation, visible right on the page — no sign-in needed. They're grouped by beginner and intermediate levels and 11 subtopics, so you can revise one part at a time. Choose Try Design Patterns quiz above to take a scored run and review the questions you got wrong.
A.Limiting how many components may access an object
B.Several parties need to know when something changes, and the source need not know who
C.Monitoring the performance of the system's components
D.Recording an object's whole change history over time
Answer: B
When many parties need to react to a change but the emitter doesn't need to know who they are: an event source, and subscribers that listen. Adding a new listener doesn't require changing the source.
A.When an object has too many constructor parameters
B.When you must guarantee only one object exists in the system
C.When the concrete class depends on data known only at runtime
D.When you need to create objects faster than usual
Answer: C
When the concrete class is chosen at runtime based on data: createPaymentGateway(method) returns the right gateway. The caller only knows the interface, and adding a new payment method doesn't require changing the caller.
B.It adds new behaviour without modifying the class
C.It gives a simple interface in front of a complex system
D.It converts one class's interface into another
Answer: C
Provides a single simple interface over a multi-step system: checkout(cart) internally calls inventory check, fee calculation, order creation, email sending. Callers don't need to know the order or the details of each step.
Two modules importing each other (circular dependency) cause what?
A.The bundle ends up containing two copies of each module
B.One side may receive an uninitialized value
C.The compiler always refuses to compile that code
D.The application runs more slowly because the module is loaded twice
Answer: B
One side may get undefined because the other module hasn't finished loading when it reads. Failures depend on load order, so they show up inconsistently and often surface somewhere unrelated to the cause.
What does the Interface Segregation Principle state?
A.Do not force a class to depend on methods it does not use
B.The interface must live in the same package as its implementation
C.Every public method must be declared in an interface
D.Each class may implement only one interface
Answer: A
No class should be forced to depend on methods it does not use. Large interfaces should be split into smaller role-based interfaces so each consumer only sees the part relevant to it.
A.Add new behaviour with new code rather than editing the old
B.Every method must be declared public
C.Every class must be declared inheritable
D.Code may not be edited once it is in production
Answer: A
A unit of code should be open for extension but closed for modification: add new behavior by writing new code rather than changing existing code. This is usually achieved through interfaces and polymorphism, not necessarily inheritance.
A.Several small classes are merged into one larger one
B.The necessary libraries are loaded automatically at runtime
C.Dependencies are supplied from outside rather than created internally
D.Every dependency becomes a global variable
Answer: C
A class receives its dependencies from outside — usually via the constructor — instead of instantiating them internally. As a result it does not depend on a concrete implementation, can be swapped at the composition point, and can be tested with a fake.
A.A value object always has fewer fields than an entity
B.An entity is stored in the database while a value object is not
C.A value object compares by value while an entity compares by identity
D.A value object may not have methods
Answer: C
An entity has its own identity and keeps that identity even as its fields change. A value object has no identity, two objects with the same value are considered equal, and it is usually designed to be immutable.
A.Traversing the elements without exposing the internal structure
B.Sorting the elements into a desired order
C.Reducing the memory the collection occupies
D.Letting several threads modify the collection safely
Answer: A
It separates traversal from storage structure: the caller uses a common interface to walk through elements without knowing whether the internals are an array, tree, or linked list. Changing the internal structure does not affect consumers.
What is the main benefit of designing immutable objects?
A.It uses less memory than an ordinary object
B.It runs faster in every case
C.It cannot be modified unexpectedly through a shared reference
D.It is saved to the database automatically when it changes
Answer: C
Once created, an object does not change value, so sharing it across places and threads is safe without synchronization. To get a different value, create a new instance. The trade-off is higher memory cost under continuous updates.
A shipping-fee function has if branches for 6 carriers and grows monthly. Which pattern fits?
A.Singleton so there is only one fee calculator in the system
B.Decorator to wrap extra fee logic around the existing function
C.Strategy: one class per carrier
D.Observer to notify when the shipping fee changes
Answer: C
Strategy: define a ShippingCalculator interface, one implementing class per carrier, then pick the class based on input data. Adding a new carrier is adding one file, not touching a function that already works.
Why is Singleton considered a pattern to use sparingly?
A.It violates the single responsibility principle
B.It is hidden global state, which makes testing hard
C.It does not work in a multi-threaded environment
D.It wastes memory because the object is never released
Answer: B
It's hidden global state: a function using a singleton doesn't declare that dependency in its parameters, so reading the function signature doesn't tell you what it depends on. Tests are also hard because state can leak from a previous test.
Switching SMS provider A to B without touching business code. Which pattern?
A.Facade to wrap the whole SDK in one function
B.Adapter: your own interface with one class per provider
C.Factory to create the SMS sender whenever it is needed
D.Proxy to intercept calls to the current provider
Answer: B
Adapter (a.k.a. port/adapter): declare an interface shaped to your needs (sendSms(phone, message)), then make each provider a class implementing it. Switching providers is just injecting a different class.
What does the dependency inversion principle state?
A.A lower layer may not call a higher one
B.A class should have as few dependencies as possible
C.Both layers depend on an abstraction rather than on each other
D.Every dependency must be passed in through the constructor
Answer: C
The business layer doesn't depend on infrastructure details; both depend on an abstraction. For example, OrderService depends on the OrderRepository interface, while the Postgres class implements that interface.
Adding logging and timing to many handlers without editing each one. Which pattern?
A.Template method to define a shared processing skeleton
B.Strategy to choose the handling per function
C.Decorator: wrap the original function to add behaviour
D.Adapter to normalize the handlers' signatures
Answer: C
Decorator: withLogging(withTiming(handler)) — each wrapper adds one concern that the original function knows nothing about. In JS this is a higher-order function, and Express or Next middleware is exactly this pattern.
What does the repository pattern give over calling the ORM directly in services?
A.It lets you swap SQL for NoSQL with no changes at all
B.It automatically caches every query passing through it
C.Queries live in one place and services can be tested without a DB
D.Queries run faster thanks to centralized optimization
Answer: C
Two practical benefits: queries are centralized in one place (when the schema changes you know where to fix it, and query names express business meaning), and the service is testable with a fake repository without a real DB.
How should the single responsibility principle be understood?
A.A class should have only one public method
B.A function should be no longer than 20 lines
C.A module should have only one reason to change
D.A file should contain exactly one class
Answer: C
A module should have one reason to change — that is, serve one group of users or one concern. Reading it as "does only one thing" leads to fragmenting into hundreds of files that each say nothing.
A constructor takes 9 parameters, many optional. What is better?
A.Give every optional parameter a default value
B.Create several constructors for each combination of parameters
C.Split the class into smaller ones grouped by parameter
D.Take a named parameter object, or a builder
Answer: D
Take an object with named fields (createServer({ port, host, timeout })) — the caller reads and understands, doesn't worry about order, and adding a new option doesn't break the signature. A builder fits when construction has many steps or needs incremental validation.
An order has many states with complex transition rules. Which pattern fits?
A.Command to package each operation as its own object
B.A state machine: declare the states and the valid transitions explicitly
C.Strategy to pick the handling per state
D.Observer to notify when the order's state changes
Answer: B
State machine: declare a table of states and allowed transitions (pending → paid → shipped), and every change must go through a function that checks that table. Invalid transitions are blocked in a single place.
A.When the codebase is still under ten thousand lines
B.When the team is not yet familiar with that pattern
C.When the problem the pattern solves has not appeared yet
D.When the project uses a functional language rather than an object-oriented one
Answer: C
When the problem the pattern solves doesn't exist yet. An interface with exactly one implementation, a factory that creates exactly one type, an event bus for two modules — all are abstractions paid for in advance for a need that may never come.
What does composition over inheritance mean in practice?
A.Using interfaces instead of abstract classes everywhere
B.Assembling small components instead of a deep inheritance tree
C.Splitting a large class into smaller ones by function
D.Never using inheritance under any circumstance
Answer: B
Prefer composing small components with clear responsibilities (an object holding its collaborators) over multi-level inheritance. Inheritance forces you to take on all of the parent's behavior, including the parts you don't need.
A UserManager class with 40 methods handling everything about users. What is this called?
A.A circular dependency between the project's modules
B.A god object: one class carrying far too many responsibilities
C.Premature optimization
D.Spaghetti code: a tangled, hard-to-follow flow of control
Answer: B
God object: one class carrying every responsibility on a topic. Concrete consequences: every change touches it (constant merge conflicts), and it depends on so many things that any test has to set up the whole world.
A.Holding temporary data in memory between processing steps
B.Validating the input data
C.Speeding up data transfer between services
D.Shaping the data at the boundary, separate from the internal model
Answer: D
It shapes data crossing a boundary (API responses, incoming payloads), separate from internal entities. That way adding a DB column doesn't automatically leak into the API, and changing the API doesn't force changing the model.
When is the Liskov substitution principle violated?
A.A subclass breaks the caller when substituted for the base class
B.A subclass overrides a base class method
C.A subclass adds a method the base class does not have
D.The base class is abstract so it cannot be instantiated
Answer: A
When substituting the parent class with a subclass breaks working code: the subclass narrows the accepted conditions, throws where the parent doesn't, or returns something outside the contract. Classic example: Square extends Rectangle and then setting width also changes height.
Adding caching and permission checks before a heavy service without editing it. Which pattern?
A.Proxy: the same interface, controlling the calls to the real one
B.Adapter to convert the service's interface
C.Facade to simplify how the service is called
D.Observer to watch every call to that service
Answer: A
Proxy: an object implementing the same interface, handling the side concerns (cache, permission checks, timing, lazy loading) before forwarding the call to the real object. Callers don't know a proxy sits in between.
Domain classes hold only getters and setters, with all logic in services. What is this?
A.A domain model without behaviour
B.An inevitable consequence of using an ORM
C.A correctly layered architecture
D.A correct application of the single responsibility principle
Answer: A
This is an anemic domain model: domain classes hold only data, while business rules live in services. The same rule gets duplicated across services and drifts apart, because there is no single place that owns it.
Many UI components call each other, forming a tangled dependency web. Which pattern fits?
A.Decorator — wrapping extra behaviour around each component
B.Singleton — sharing one global instance
C.Builder — separating a complex construction process
D.Mediator — communicating through an intermediary object
Answer: D
Mediator: components don't call each other directly but notify a central object, which coordinates them. The number of links drops from quadratic to linear, and each component can be tested independently.
A.It generates queries from the object definitions
B.It groups the changes and writes them within one transaction
C.It switches between different kinds of database
D.It caches query results to avoid repeated calls
Answer: B
Repository handles access to each type of object; Unit of Work tracks all changes in a business operation and persists them in one transaction. This lets many repositories participate in one operation while preserving integrity.
A.An adapter is for external libraries and a facade for internal code
B.A facade is a newer version replacing the adapter
C.An adapter converts an interface while a facade simplifies one
D.An adapter is slower than a facade because of the conversion
Answer: C
Adapter converts the interface of an existing class to match what the caller expects — the problem is a mismatch. Facade provides a simple interface in front of a complex subsystem — the problem is that it is too cumbersome to use directly.
A.When the objects must be created in a fixed order
B.When you must guarantee only one instance exists
C.When the application creates a great many small objects
D.When creating an object is far more expensive than using it
Answer: D
When creation cost far exceeds usage cost — database connections, threads, network connections. For lightweight objects, pooling and reuse is usually slower and more complex than letting the GC do its job.
A.Easy to add new element types but hard to add operations
B.Faster to run but heavier on memory
C.Shorter code but harder to test
D.Easy to add operations, hard to add new element types
Answer: D
It inverts what is easy to extend: adding a new operation only requires a new visitor, but adding a new element type forces changes to every existing visitor. It fits when the set of element types is stable while the number of operations grows.
How does in-process observer differ from pub/sub over a message broker?
A.An observer must be declared in advance while pub/sub need not
B.Pub/sub guarantees ordering while an observer does not
C.An observer supports many receivers while pub/sub supports one
D.An observer is synchronous within the process while pub/sub is not
Answer: D
Observer calls directly within the same process and is usually synchronous: if a receiver fails, the publisher is affected, and there is no delay. Pub/sub goes through a broker, so the two sides are fully decoupled, but it adds latency and possible duplication.
What principle does order.getCustomer().getAddress().getCity().getName() violate?
A.The Liskov substitution principle
B.The single responsibility principle of the calling class
C.The principle of least knowledge between objects
D.The interface segregation principle
Answer: C
It violates the Law of Demeter: an object should only talk to its immediate neighbors, not reach through multiple layers. This call chain depends on the internal structure of four classes, so any of them changing its structure breaks it.
You need a nested category tree treating leaves and branches uniformly. Which pattern?
A.Decorator — wrapping extra behaviour on each node
B.Composite — leaves and branches share one interface
C.Strategy — extracting the traversal algorithm
D.Proxy — controlling access to each node
Answer: B
Composite: individual elements and groups of elements implement the same interface, and a group can contain other groups. The caller treats both the same way, so recursive code doesn't need to distinguish cases.
Two modules contain identical code. When should it NOT be merged?
A.When the two modules were written by two different people
B.When the two pieces sit in different files in the project
C.When the two pieces are alike by coincidence
D.When the duplicated code runs longer than twenty lines
Answer: C
When the two pieces are coincidentally similar rather than the same business rule. Merging them creates a dependency between two unrelated modules, and whenever one side changes, the shared function needs another conditional parameter, ending up harder to understand than two separate copies.
How does a circuit breaker protect the calling system?
A.It stops calling temporarily once the failure rate crosses a threshold
B.It redirects the calls to a standby server
C.It retries failed calls until they succeed
D.It limits how many calls per second reach the service
Answer: A
When the error rate crosses a threshold, it stops calling and fails immediately for a period of time. That way the caller doesn't pile up threads waiting to time out, and the failing side gets no extra load so it has a chance to recover.
Why is constructor injection usually preferred over field injection?
A.The dependencies appear in the signature and the object is always valid
B.It makes the application start faster
C.It avoids circular dependencies between classes
D.It allows swapping dependencies at runtime
Answer: A
Dependencies show up in the constructor signature, so you can't create an object missing what it needs, and the object is always valid right after creation. Tests can instantiate it directly, with no framework or reflection to set fields.