Design Patterns Questions with Answers

33 practice questions on Design Patterns (OOP Concepts) with answers and step-by-step solutions. Try 10 samples below, then practise all 33 free in the AptiNest app.

Sample questions

Question 1Easy

Which pattern lets you traverse the elements of a collection without exposing its internal representation?

  1. Composite
  2. Visitor
  3. Command
  4. Iterator

Answer: D. Iterator

Explanation

An Iterator offers hasNext()/next() style access, so clients don't depend on whether the collection is an array, list or tree.

Step-by-step solution

  1. Iterator provides methods like hasNext() and next() to traverse collections.
  2. These methods hide how elements are stored inside the collection.
  3. Clients use Iterator without knowing if the collection is a list, tree, or array.
  4. This pattern ensures internal structure remains unchanged by clients.
  5. Thus, Iterator lets you traverse elements without exposing internal representation.

Why the other options are wrong

  • A. Composite groups objects into tree structures and treats them uniformly; it does not provide a way to traverse a collection.
  • B. Visitor adds new operations to element classes without changing them; it does not traverse a collection's elements one by one.
  • C. Command wraps a request as an object so it can be queued or undone; it does not traverse the elements of a collection.

Tip: Use Iterator when you need to access elements of a collection without exposing its internal structure.

Question 2Easy

Java's java.io stream classes, such as new BufferedReader(new FileReader(f)), are a well-known example of:

  1. Decorator
  2. Singleton
  3. Observer
  4. Prototype

Answer: A. Decorator

Explanation

Each wrapper adds behaviour (buffering, line reading) to a reader while still being a Reader itself.

Step-by-step solution

  1. BufferedReader wraps FileReader to add buffering functionality.
  2. This allows multiple behaviors to be added without changing the original class.
  3. Each wrapper maintains the same interface as the base class.
  4. This pattern is known as Decorator in object-oriented design.
  5. Decorator adds responsibilities at runtime without modifying existing code.
  6. Final answer: Decorator.

Why the other options are wrong

  • B. Singleton ensures a class has only one instance; wrapping streams in other streams is not about a single shared instance.
  • C. Observer lets one object notify subscribers of changes; java.io stream wrapping does not notify any observers.
  • D. Prototype creates objects by cloning; BufferedReader does not clone FileReader, it wraps it to add buffering.

Tip: Remember, Decorator adds behavior without changing the original class structure.

Question 3Easy

What is the output of this Java program?

abstract class Game {
    final void play() { start(); turn(); end(); }
    void start() { System.out.print("start "); }
    abstract void turn();
    void end() { System.out.print("end"); }
}
class Chess extends Game {
    void turn() { System.out.print("move "); }
    void end() { System.out.print("checkmate"); }
}
public class Main {
    public static void main(String[] args) { new Chess().play(); }
}
  1. start move checkmate
  2. start move end checkmate
  3. start move end
  4. move checkmate

Answer: A. start move checkmate

Explanation

Template Method: play() fixes the step order, Chess supplies turn() and overrides end(), while start() comes from Game.

Step-by-step solution

  1. New Chess().play() runs the final play() method.
  2. It calls start(), which is not overridden, so it prints "start ".
  3. It calls turn() from Chess, which prints "move ".
  4. It calls end(), which Chess overrides to print "checkmate"; output "start move checkmate", index 0.

Why the other options are wrong

  • B. end() is overridden in Chess, so the base text "end" is never printed.
  • C. Chess's end() prints checkmate, not end.
  • D. start() is not overridden, so "start " is printed first.

Tip: A final template method runs its steps in fixed order; overridden steps use the subclass's version.

Question 4Easy

What is the output of this Java program?

import java.util.function.*;
class Calculator {
    private IntBinaryOperator op;
    Calculator(IntBinaryOperator op) { this.op = op; }
    void setOp(IntBinaryOperator op) { this.op = op; }
    int run(int a, int b) { return op.applyAsInt(a, b); }
}
public class Main {
    public static void main(String[] args) {
        Calculator c = new Calculator((a, b) -> a + b);
        int r1 = c.run(6, 3);
        c.setOp((a, b) -> a * b);
        System.out.println(r1 + " " + c.run(6, 3));
    }
}
  1. 9 9
  2. 18 18
  3. 9 18
  4. 18 9

Answer: C. 9 18

Explanation

This is the Strategy pattern: the algorithm object is swapped at runtime. The first run adds (9); after setOp the second multiplies (18).

Step-by-step solution

  1. The calculator starts with the add lambda: run(6, 3) gives 9, stored in r1.
  2. SetOp swaps in the multiply lambda.
  3. run(6, 3) now gives 6 × 3 = 18, so the line prints "9 18"; index 2 is correct.

Why the other options are wrong

  • A. The second value is 18 after setOp, not 9.
  • B. R1 was computed before the swap, so it is 9, not 18.
  • D. The order is wrong; r1 is printed first.

Tip: Expressions run in order; a value stored earlier does not change when the operator is swapped later.

Question 5Medium

In MVC, which component handles user input and updates the model?

  1. View
  2. Model
  3. Router table
  4. Controller

Answer: D. Controller

Explanation

The controller interprets input and calls the model; the view renders model data; the model holds data and business logic.

Step-by-step solution

  1. Controller receives user input from the view.
  2. Controller processes input and updates the model.
  3. Controller interacts with the model to fetch data.
  4. Controller sends updated data to the view.
  5. Final answer: Controller.

Why the other options are wrong

  • A. The View only displays data to the user; it does not handle input or update the model.
  • B. The Model holds data and business rules; it is updated by the Controller and does not receive user input directly.
  • C. Router table is not one of the three MVC components, so it cannot be the part that handles input and updates the model.

Tip: Remember: Controller manages input and model changes.

Question 6Medium

Event listeners in GUI frameworks, where many handlers subscribe to a button's click events, follow which pattern?

  1. Command
  2. Observer
  3. Mediator
  4. Iterator

Answer: B. Observer

Explanation

The button (subject) keeps a list of listeners (observers) and notifies all of them when an event occurs.

Step-by-step solution

  1. Button holds list of click handlers.
  2. Handlers are notified when button is clicked.
  3. This matches observer pattern definition.
  4. Observer pattern uses subject and observers.
  5. Final answer: B (Observer).

Why the other options are wrong

  • A. Command encapsulates a request as an object; it does not keep a list of subscribers that are notified on each event.
  • C. Mediator centralises communication between objects; a button simply keeps a list of handlers, which is the observer idea.
  • D. Iterator walks through the elements of a collection one by one; it does not notify handlers when an event happens.

Tip: Remember: event handling in GUI follows observer pattern.

Question 7Medium

Which pattern provides a placeholder that controls access to another object, for example to load an image lazily or check permissions?

  1. Decorator
  2. Proxy
  3. Facade
  4. Adapter

Answer: B. Proxy

Explanation

A Proxy has the same interface as the real subject and controls when and how it is accessed (virtual, protection or remote proxy).

Step-by-step solution

  1. Proxy acts as a placeholder for another object.
  2. It controls access to the actual object.
  3. This is used for lazy loading or permission checks.
  4. Example: Image loading with Proxy.
  5. Proxy ensures safe and controlled access.
  6. Final answer: B (Proxy).

Why the other options are wrong

  • A. Decorator adds new behaviour to an object; it does not control access to another object or act as its placeholder.
  • C. Facade gives a simplified interface to a whole subsystem; it does not stand in for a single object to control access.
  • D. Adapter converts one interface into the one a client expects; it does not control access to the wrapped object.

Tip: Use Proxy for controlled access or lazy initialization.

Question 8Medium

Which pattern provides an interface for creating families of related objects (e.g. WinButton + WinCheckbox, or MacButton + MacCheckbox) without naming concrete classes?

  1. Abstract Factory
  2. Builder
  3. Prototype
  4. Factory Method

Answer: A. Abstract Factory

Explanation

An Abstract Factory has one creation method per product type, and each concrete factory produces a matching family.

Step-by-step solution

  1. Abstract Factory creates families of related objects.
  2. It defines interfaces for creating products.
  3. Each concrete factory implements these interfaces.
  4. This ensures consistent object creation across families.
  5. Final answer: Abstract Factory.

Why the other options are wrong

  • B. Builder constructs one complex object step by step; it does not provide an interface for creating families of related objects.
  • C. Prototype creates new objects by cloning an existing instance, so it does not create families of related products.
  • D. Factory Method creates one product through a subclass-overridden method, not a whole family of related objects.

Tip: Use Abstract Factory when you need multiple related objects with common interfaces.

Question 9Hard

Why is a naive lazily-initialised Singleton (if (instance == null) instance = new X();) unsafe in multithreaded code?

  1. The constructor will run before main() and fail because no threads exist yet
  2. Two threads can both see null and create two instances
  3. The instance can never be garbage-collected
  4. Static methods cannot be called from threads

Answer: B. Two threads can both see null and create two instances

Explanation

The check-then-create sequence is a race. Fixes include eager initialisation, synchronisation, the holder-class idiom, or (in Java) an enum singleton.

Step-by-step solution

  1. Thread A checks instance == null and sees true.
  2. Before A assigns the new object, thread B also checks and also sees null.
  3. Both create a new object, so two instances exist. The answer: two threads can both see null.

Why the other options are wrong

  • A. Constructors run when an instance is created, not before main, so this is not the cause.
  • C. Garbage collection depends on references, and it is not what breaks the lazy check.
  • D. Static methods can be called from any thread; that is not the problem.

Tip: Make a lazy singleton thread-safe with synchronized, a holder class, or an enum.

Question 10Hard

What does this Python code print?

class Single:
    _inst = None
    def __new__(cls):
        if cls._inst is None:
            cls._inst = super().__new__(cls)
        return cls._inst
    def __init__(self):
        self.calls = getattr(self, "calls", 0) + 1

a = Single()
b = Single()
print(a is b, b.calls)
  1. True 2
  2. False 2
  3. True 1
  4. False 1

Answer: A. True 2

Explanation

__new__ returns the same instance every time, but __init__ still runs on each Single() call, so calls becomes 2.

Step-by-step solution

  1. a = Single(): __new__ sees cls._inst is None, creates the instance and stores it; __init__ then runs, setting self.calls = 0 + 1 = 1.
  2. b = Single(): __new__ now sees cls._inst already set, so it returns that SAME existing object.
  3. Python always calls __init__ again on whatever __new__ returns, even if it's the same object, so __init__ runs again: self.calls = getattr(self, "calls", 0) + 1 = 1 + 1 = 2.
  4. a is b is True, since both calls ultimately returned the identical object.

Why the other options are wrong

  • B. a is b is True, not False - __new__ always returns the same stored object once cls._inst is set.
  • C. b.calls is 2, not 1 - __init__ runs again on the second call even though no new object was created.
  • D. This combines both wrong claims above; neither condition holds.

Tip: A DIY Python singleton via __new__ alone still re-runs __init__ on every call - guard __init__ too (e.g. with a flag) if state shouldn't reset.

Practise all 33 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all OOP Concepts topics · All topics