Skip to lesson

Design patterns interview questions

In an interview someone says "explain Strategy" or "write a thread-safe singleton". You already built both in ShopLite, but a rambling answer loses the marks. A fixed answer shape fixes that.

How to answer: intent, structure, example, trade-off

A four-part answer explains a pattern as intent (the problem it solves), structure (the main roles), example (one real case) and trade-off (what it costs). It takes about a minute to say.

Below is a Strategy answer written as comments around real code, one comment for each part of the four-part answer.

Example 1 · A four-part answer, written as code

FourPartAnswerDemo.javaJava
import java.util.Map;
// INTENT: choose one of several ways to compute a discount at runtime, without if-else chains.// STRUCTURE: an interface (strategy), classes per rule, and a context that holds one.interface DiscountStrategy {    int discount(int total);}
class FestivalDiscount implements DiscountStrategy {    public int discount(int total) { return total / 10; }}
class FlatCoupon implements DiscountStrategy {    public int discount(int total) { return total >= 999 ? 150 : 0; }}
class Cart {    private final int total;    private final DiscountStrategy strategy;
    Cart(int total, DiscountStrategy strategy) {        this.total = total;        this.strategy = strategy;    }
    int payable() { return total - strategy.discount(total); }}
// EXAMPLE + TRADE-OFF: ShopLite picks the rule by campaign code; for two fixed rules an if is enough.public class FourPartAnswerDemo {    public static void main(String[] args) {        Map<String, DiscountStrategy> campaigns = Map.of("DIWALI", new FestivalDiscount(), "FLAT150", new FlatCoupon());        System.out.println("DIWALI on Rs. 1200: Rs. " + new Cart(1200, campaigns.get("DIWALI")).payable());        System.out.println("FLAT150 on Rs. 1200: Rs. " + new Cart(1200, campaigns.get("FLAT150")).payable());    }}
Output
DIWALI on Rs. 1200: Rs. 1080
FLAT150 on Rs. 1200: Rs. 1050

What this code does

  • The comments carry the intent, the structure and the trade-off. The code is the structure part.
  • The campaign map shows the real example: the rule is chosen at run time by its code.

The trade-off is what separates a memorised answer from an understood one. Keep the whole answer to about a minute, and offer to write the code.

Predict the output

Which part is this?

Match each sentence to a part of the four-part answer.

Round 1 of 2

The next sentence is which part?

Answer so far: "Strategy lets us pick a discount rule at run time."
Next sentence: "It costs one class per rule; for two fixed rules a plain if is enough."
If you blank on a name, describe the intent and structure in plain words. Interviewers care more about the design idea than the label.

Frequent questions: singleton, factory vs abstract factory, builder

The holder idiom is a thread-safe lazy singleton: a private nested class holds the instance, and the JVM loads that class once, on first use, safely for every thread.

Two classic questions are the thread-safe singleton and factory versus abstract factory. The code below shows two safe singletons, then both factory kinds.

Example 2 · Two thread-safe singleton answers

SingletonAnswersDemo.javaJava
// Answer 1: initialization-on-demand holder. Lazy and thread-safe, no locks on each call.class AppConfig {    private AppConfig() {        System.out.println("AppConfig loaded");    }
    private static class Holder {        static final AppConfig INSTANCE = new AppConfig();   // created when Holder is first used    }
    static AppConfig getInstance() {        return Holder.INSTANCE;    }}
// Answer 2: enum singleton. Thread-safe and safe against reflection and serialization.enum IdGenerator {    INSTANCE;
    private int next = 1000;
    synchronized int nextOrderId() {        return next++;    }}
public class SingletonAnswersDemo {    public static void main(String[] args) throws InterruptedException {        System.out.println("Before first use");        Thread t1 = new Thread(AppConfig::getInstance);        Thread t2 = new Thread(AppConfig::getInstance);        t1.start();        t2.start();        t1.join();        t2.join();        System.out.println("Same instance: " + (AppConfig.getInstance() == AppConfig.getInstance()));
        System.out.println("Order ids: " + IdGenerator.INSTANCE.nextOrderId() + ", " + IdGenerator.INSTANCE.nextOrderId());    }}
Output
Before first use
AppConfig loaded
Same instance: true
Order ids: 1000, 1001

What this code does

  • The holder idiom creates AppConfig only when getInstance() first touches Holder, and the JVM's class loading guarantees that happens once even with two threads.
  • The enum singleton is the simplest safe version; its synchronized method keeps the order-id counter correct across threads.

Example 3 · Factory vs Abstract Factory

FactoryVsAbstractFactoryDemo.javaJava
// Factory: ONE product, chosen by a parameterinterface PaymentMethod { String pay(int amount); }class UpiPayment implements PaymentMethod { public String pay(int a) { return "UPI Rs. " + a; } }class CardPayment implements PaymentMethod { public String pay(int a) { return "Card Rs. " + a; } }
class PaymentFactory {    static PaymentMethod create(String type) {        return switch (type) {            case "UPI" -> new UpiPayment();            case "CARD" -> new CardPayment();            default -> throw new IllegalArgumentException("Unknown payment type: " + type);        };    }}
// Abstract Factory: a FAMILY of products that must match each otherinterface TaxCalculator { int tax(int amount); }interface PriceFormatter { String format(int amount); }
interface StoreFactory {    TaxCalculator taxCalculator();    PriceFormatter priceFormatter();}
class IndiaStoreFactory implements StoreFactory {    public TaxCalculator taxCalculator() { return a -> a * 18 / 100; }    public PriceFormatter priceFormatter() { return a -> "Rs. " + a; }}
class UsStoreFactory implements StoreFactory {    public TaxCalculator taxCalculator() { return a -> a * 8 / 100; }    public PriceFormatter priceFormatter() { return a -> "$" + a; }}
public class FactoryVsAbstractFactoryDemo {    static void bill(StoreFactory store, int amount) {        TaxCalculator tax = store.taxCalculator();        PriceFormatter fmt = store.priceFormatter();        System.out.println("Bill: " + fmt.format(amount) + " + tax " + fmt.format(tax.tax(amount)));    }
    public static void main(String[] args) {        System.out.println(PaymentFactory.create("UPI").pay(499));        bill(new IndiaStoreFactory(), 1000);        bill(new UsStoreFactory(), 1000);    }}
Output
UPI Rs. 499
Bill: Rs. 1000 + tax Rs. 180
Bill: $1000 + tax $80

What this code does

  • PaymentFactory.create returns one product chosen by a string.
  • StoreFactory returns a matching tax calculator and price formatter together, so an Indian bill can never be printed in dollars.

Singleton thread safety: a lazy if (instance == null) instance = new X(); can create two objects when two threads run it together. Good answers are the holder idiom, an enum singleton or eager creation. In Spring you rarely write one: singleton-scoped beans give one instance per container.

Factory vs Abstract Factory: a factory creates one kind of product chosen by a parameter; an Abstract Factory creates a family of products that must match, such as an Indian tax calculator with a rupee formatter. Builder suits many optional fields plus validation; for two or three required fields, use a constructor or a record.

Find the bug

Find the interview trap

Click the line that causes the problem.

Two threads call getInstance() at the same time. Which line can create two objects?

Round 1 of 2

'Which patterns have you used?' with ShopLite examples

Answer with your own project: one pattern per real problem, in two sentences each. The list below shows a strong ShopLite set, including one pattern not used.

Text
// Strategy:  ShippingOption -> Standard, Express, StorePickup (chosen by the customer)// State:     OrderState -> Placed, Paid, Shipped, Delivered, Cancelled (illegal moves rejected)// Adapter:   PayNowAdapter implements PaymentGateway (SDK in paise, our API in rupees)// Decorator: LoggingGateway(RetryGateway(adapter)) around any PaymentGateway// Observer:  OrderEvents -> email, stock and analytics listeners// Not used:  GST stays one plain method; one rule did not need a Strategy

Pick three or four, not ten, and be ready for "why not a simple if?" for each one. Mention one place where you chose not to use a pattern; it shows judgement.

Patterns in Java and Spring questions

Framework questions check that you see patterns in tools you already use. Prepare one line for each pattern in the list below.

Text
// Java:   Iterator (for-each), Strategy (Comparator), Decorator (BufferedReader),//         Adapter (InputStreamReader), Factory (List.of), Builder (HttpRequest.newBuilder)// Spring: Factory (ApplicationContext, @Bean), singleton scope, Proxy (@Transactional),//         Template (JdbcTemplate), Chain (SecurityFilterChain), Observer (@EventListener)

The follow-up is often about a trap: why @Transactional is ignored on a self-call (the proxy is skipped), or why a Spring singleton must not hold per-user state (it is shared by all requests).

Predict the output

The self-call trap

Read the Spring class and answer.

Round 1 of 2

Another bean calls checkout(). Does pay() run inside a transaction?

@Service
class OrderService {
@Transactional
public void pay(Order o) { /* update order and stock */ }
public void checkout(Order o) { pay(o); }
}

Coding a pattern on a whiteboard in ten minutes

Whiteboard code should be small, complete and readable. The two programs below, an Observer and a Builder with validation, are short enough to write in ten minutes.

  1. Say the intent in one sentence and confirm the scenario.
  2. Write the interface first, then two implementations.
  3. Write the context or client class.
  4. Write a short main and trace its output aloud.
  5. Mention one trade-off or extension.

Example 4 · Whiteboard: Observer in under 30 lines

WhiteboardObserverDemo.javaJava
import java.util.ArrayList;import java.util.List;
record OrderPlaced(String orderId, String customer) { }
interface OrderListener {    void onOrderPlaced(OrderPlaced event);}
class OrderEvents {    private final List<OrderListener> listeners = new ArrayList<>();
    void subscribe(OrderListener l) { listeners.add(l); }
    void publish(OrderPlaced event) {        for (OrderListener l : listeners) {            l.onOrderPlaced(event);        }    }}
public class WhiteboardObserverDemo {    public static void main(String[] args) {        OrderEvents events = new OrderEvents();        events.subscribe(e -> System.out.println("Email to " + e.customer() + ": " + e.orderId() + " confirmed"));        events.subscribe(e -> System.out.println("Stock reserved for " + e.orderId()));        events.subscribe(e -> System.out.println("Analytics: +1 order"));        events.publish(new OrderPlaced("ORD-101", "riya@example.com"));    }}
Output
Email to riya@example.com: ORD-101 confirmed
Stock reserved for ORD-101
Analytics: +1 order

What this code does

  • An event record, a listener interface, a subject with subscribe and publish, and three lambda listeners: the full pattern.
  • On a whiteboard this is enough; mention listener errors and unsubscribing as follow-ups.

Example 5 · Whiteboard: Builder with validation

WhiteboardBuilderDemo.javaJava
import java.util.ArrayList;import java.util.List;
final class Order {    private final String customer;    private final List<String> items;    private final String coupon;          // optional    private final boolean giftWrap;       // optional
    private Order(Builder b) {        customer = b.customer;        items = List.copyOf(b.items);        coupon = b.coupon;        giftWrap = b.giftWrap;    }
    static Builder builder(String customer) { return new Builder(customer); }
    @Override    public String toString() {        return customer + " " + items + (coupon == null ? "" : " coupon=" + coupon) + (giftWrap ? " gift-wrapped" : "");    }
    static final class Builder {        private final String customer;        private final List<String> items = new ArrayList<>();        private String coupon;        private boolean giftWrap;
        private Builder(String customer) { this.customer = customer; }
        Builder item(String name) { items.add(name); return this; }        Builder coupon(String code) { coupon = code; return this; }        Builder giftWrap() { giftWrap = true; return this; }
        Order build() {            if (items.isEmpty()) throw new IllegalStateException("an order needs at least one item");            return new Order(this);        }    }}
public class WhiteboardBuilderDemo {    public static void main(String[] args) {        System.out.println(Order.builder("Riya").item("Earbuds").item("Notebook").coupon("FEST10").build());        System.out.println(Order.builder("Kabir").item("Hoodie").giftWrap().build());        try {            Order.builder("Meera").build();        } catch (IllegalStateException e) {            System.out.println("Error: " + e.getMessage());        }    }}
Output
Riya [Earbuds, Notebook] coupon=FEST10
Kabir [Hoodie] gift-wrapped
Error: an order needs at least one item

What this code does

  • The required customer goes into builder(customer); optional parts are chained; build() checks the rule and makes an immutable Order.
  • List.copyOf keeps the order's item list safe from later changes to the builder.

Say what you are writing as you write it, and leave out getters, logging and error handling unless asked.

Practise a few by heart until each takes under ten minutes: Strategy, Observer, Builder with validation, a thread-safe Singleton, Decorator and a Command with undo. Finish by tracing your main aloud, line by line, to show the output.

Next step

Check your understanding

12 quick questions