Design patterns section review
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Every pattern in this section answers one question: "what changes here, and how do I keep that change in one place?" Creational patterns control how objects are made, structural patterns how they are wrapped and combined, and behavioural patterns how they share work and react to events.
Creational and structural patterns at a glance
A creational pattern controls how objects are created, so callers do not depend on exact classes or long constructors.
A structural pattern wraps or combines objects so they fit together: a new interface over an old one, extra behaviour around an object, or one simple door in front of many classes.
Pattern Intent (one line) ShopLite useSingleton exactly one instance, global access AppConfig as an enumFactory Method a method decides which class to create PaymentMethodFactory.create("UPI")Abstract Factory families of related objects that go together test vs live payment + SMS kitsBuilder build a complex object step by step Order.builder()...build()Prototype copy a ready object instead of building again copy an order templateAdapter make an existing class fit the interface we use old SMS gateway -> NotificationServiceDecorator add behaviour by wrapping, same interface logging / retry around a notifierProxy stand-in that controls access to the real one caching ProductCatalog, @TransactionalFacade one simple entry point over many classes CheckoutFacade.placeOrder(...)Composite treat a group like a single item a combo bundle of productsExample 1 · Creational and structural patterns in one checkout
import java.util.ArrayList;import java.util.List;
interface NotificationService { void send(String to, String text); }
// Adapter: the old SDK has a different method shapeclass LegacySmsSdk { void sendSms(String number, String text, int priority) { System.out.println(" [sdk p" + priority + "] " + number + ": " + text); }}
class SmsAdapter implements NotificationService { private final LegacySmsSdk sdk = new LegacySmsSdk(); public void send(String to, String text) { sdk.sendSms(to, text, 1); }}
// Decorator: adds logging, same interface, wraps another notifierclass LoggingNotifier implements NotificationService { private final NotificationService inner; LoggingNotifier(NotificationService inner) { this.inner = inner; } public void send(String to, String text) { System.out.println(" log: sending to " + to); inner.send(to, text); }}
final class Order { final String customer; final List<String> items; final String coupon; private Order(Builder b) { customer = b.customer; items = List.copyOf(b.items); coupon = b.coupon; } static Builder builder(String customer) { return new Builder(customer); } static final class Builder { private final String customer; private final List<String> items = new ArrayList<>(); private String coupon = "none"; private Builder(String customer) { this.customer = customer; } Builder item(String sku) { items.add(sku); return this; } Builder coupon(String c) { coupon = c; return this; } Order build() { return new Order(this); } }}
// Singleton: one shared configurationenum AppConfig { INSTANCE; final int freeShippingFrom = 499;}
public class CreationalStructuralDemo { public static void main(String[] args) { Order order = Order.builder("98450 11111").item("MUG").item("CAP").coupon("SAVE10").build(); NotificationService notifier = new LoggingNotifier(new SmsAdapter()); System.out.println("Order for " + order.customer + ": " + order.items + ", coupon " + order.coupon); System.out.println("Free shipping from Rs " + AppConfig.INSTANCE.freeShippingFrom); notifier.send(order.customer, "Order placed"); }}Order for 98450 11111: [MUG, CAP], coupon SAVE10 Free shipping from Rs 499 log: sending to 98450 11111 [sdk p1] 98450 11111: Order placed
What this code does
SmsAdapterimplements ourNotificationServicebut calls the old SDK'ssendSmsinside: that shape is an Adapter.LoggingNotifierimplements the same interface and holds another one, adding a log line before passing the call on: a Decorator. The two stack because both areNotificationServices.- The builder names every order part, and the enum gives exactly one
AppConfiginstance, the simplest safe Singleton in Java.
For each pattern, remember three things: the intent (the problem it solves, in one line), the structure (which interface and classes it needs) and one ShopLite use. If you can say all three, you can use it in an interview.
Behavioural patterns at a glance
A behavioural pattern decides how objects share work and react to events.
Behavioural patterns most often replace a growing if/switch with objects: one object per rule (Strategy), per state (State), per step in a fixed recipe (Template Method), per request handler (Chain of Responsibility) or per action (Command).
Pattern Intent (one line) ShopLite useStrategy swap one rule for another at runtime DiscountStrategy, ShippingStrategyObserver tell many listeners when something happens OrderPlaced -> email, SMS, stockTemplate Method fixed steps, subclasses fill some in report: header, rows, footerCommand an action as an object (queue, log, undo) AddToCartCommand with undoChain of Responsibility pass a request along handlers until handled checkout validatorsState behaviour changes with the object's state order PLACED -> SHIPPED, vending machineIterator walk a collection without knowing its insides for-each over a cartExample 2 · Behavioural patterns: chain of checks and an undoable command
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;import java.util.List;import java.util.Optional;
// Chain of Responsibility: each check passes the cart on or stops itabstract class CheckoutCheck { private CheckoutCheck next; CheckoutCheck then(CheckoutCheck next) { this.next = next; return next; } Optional<String> check(List<String> cart, int total) { Optional<String> problem = problem(cart, total); if (problem.isPresent() || next == null) return problem; return next.check(cart, total); } abstract Optional<String> problem(List<String> cart, int total);}
class NotEmpty extends CheckoutCheck { Optional<String> problem(List<String> cart, int total) { return cart.isEmpty() ? Optional.of("cart is empty") : Optional.empty(); }}
class CodLimit extends CheckoutCheck { Optional<String> problem(List<String> cart, int total) { return total > 2000 ? Optional.of("cash on delivery limit is Rs 2000") : Optional.empty(); }}
// Command: an action as an object, so it can be undoneinterface CartCommand { void run(); void undo(); }
class AddToCart implements CartCommand { private final List<String> cart; private final String sku; AddToCart(List<String> cart, String sku) { this.cart = cart; this.sku = sku; } public void run() { cart.add(sku); } public void undo() { cart.remove(sku); }}
public class BehaviouralDemo { public static void main(String[] args) { List<String> cart = new ArrayList<>(); Deque<CartCommand> history = new ArrayDeque<>(); for (String sku : List.of("MUG", "CAP", "LAPTOP")) { CartCommand add = new AddToCart(cart, sku); add.run(); history.push(add); } System.out.println("Cart: " + cart); history.pop().undo(); System.out.println("After undo: " + cart);
CheckoutCheck checks = new NotEmpty(); checks.then(new CodLimit()); System.out.println("Rs 650 COD: " + checks.check(cart, 650).orElse("ok")); System.out.println("Rs 2600 COD: " + checks.check(cart, 2600).orElse("ok")); System.out.println("Empty cart: " + checks.check(List.of(), 0).orElse("ok")); }}Cart: [MUG, CAP, LAPTOP] After undo: [MUG, CAP] Rs 650 COD: ok Rs 2600 COD: cash on delivery limit is Rs 2000 Empty cart: cart is empty
What this code does
- Each
AddToCartis an object that knows how to run and undo itself; a stack of them gives "undo the last action" for free. - The checks are linked with
then: each one either reports a problem and stops the chain, or passes the cart to the next. A new check is a new class inserted in the chain. - Strategy, Observer, State and Template Method appear in the mixed program in Example 3.
Two pairs are often confused. Strategy and State both put behaviour behind an interface, but the client picks a strategy, while a state object switches itself. Decorator and Proxy both wrap an object with the same interface, but a decorator adds behaviour, while a proxy controls access (caching, security, transactions).
Pattern selection: from scenario to pattern
Pattern selection starts from the requirement, never from the pattern list.
Find the phrase that describes change or variation ("types will grow", "tell everyone", "depends on status", "old library", "many optional fields"), and match it to the pattern built for that change.
"Payment types will grow" -> Strategy (+ Factory to create them)"Email, SMS and stock react to orders" -> Observer"Cancel allowed only before shipping" -> State"Old SMS SDK has a different method" -> Adapter"Log every call without editing it" -> Decorator (or Proxy for access control)"Checkout: stock, address, limit checks" -> Chain of Responsibility"Order with many optional parts" -> Builder"One call for the whole checkout" -> Facade"Undo the last cart action" -> Command"Same report steps, different formats" -> Template MethodIf no phrase describes change, the right answer is usually a plain class. Saying "I would not use a pattern here, because nothing varies" is a strong interview answer.
Predict the output
Pick the pattern
Read the requirement and choose the pattern built for that change.
Round 1 of 3
ShopLite will add Paytm, net banking and EMI over the next year.
Code reading: name the patterns in a mixed program
Pattern reading is the reverse skill: looking at real code and naming the patterns by their shape.
The example below is a small ShopLite checkout that uses seven patterns. Name each one before you read the explanation.
Example 3 · Name the patterns: a mixed ShopLite checkout
import java.util.ArrayList;import java.util.List;
interface PaymentMethod { boolean pay(int amount); }
class UpiPayment implements PaymentMethod { public boolean pay(int amount) { System.out.println(" UPI collect Rs " + amount); return true; }}
class OldCardGateway { int chargeInPaise(long paise) { System.out.println(" gateway charged " + paise + " paise"); return 0; }}
class CardPayment implements PaymentMethod { private final OldCardGateway gateway = new OldCardGateway(); public boolean pay(int amount) { return gateway.chargeInPaise(amount * 100L) == 0; }}
class PaymentMethods { static PaymentMethod create(String type) { return switch (type) { case "UPI" -> new UpiPayment(); case "CARD" -> new CardPayment(); default -> throw new IllegalArgumentException("Unknown payment " + type); }; }}
interface ShippingRule { int cost(int subtotal); }
interface OrderListener { void paid(String orderId, int amount); }
enum Status { NEW { Status next() { return PAID; } }, PAID { Status next() { return SHIPPED; } }, SHIPPED { Status next() { throw new IllegalStateException("already shipped"); } }; abstract Status next();}
class CheckoutFacade { private final ShippingRule shipping; private final List<OrderListener> listeners = new ArrayList<>(); CheckoutFacade(ShippingRule shipping) { this.shipping = shipping; } void onPaid(OrderListener l) { listeners.add(l); }
Status placeOrder(String orderId, int subtotal, String paymentType) { Status status = Status.NEW; int total = subtotal + shipping.cost(subtotal); if (PaymentMethods.create(paymentType).pay(total)) { status = status.next(); listeners.forEach(l -> l.paid(orderId, total)); } return status; }}
public class NameThePatternsDemo { public static void main(String[] args) { CheckoutFacade checkout = new CheckoutFacade(subtotal -> subtotal >= 499 ? 0 : 40); checkout.onPaid((id, amount) -> System.out.println(" SMS: " + id + " paid Rs " + amount)); checkout.onPaid((id, amount) -> System.out.println(" Stock reserved for " + id));
System.out.println("SL-1 -> " + checkout.placeOrder("SL-1", 350, "UPI")); System.out.println("SL-2 -> " + checkout.placeOrder("SL-2", 1200, "CARD")); }}UPI collect Rs 390 SMS: SL-1 paid Rs 390 Stock reserved for SL-1 SL-1 -> PAID gateway charged 120000 paise SMS: SL-2 paid Rs 1200 Stock reserved for SL-2 SL-2 -> PAID
What this code does
- Strategy:
PaymentMethodandShippingRule(a lambda here). Factory:PaymentMethods.create("UPI"). Adapter:CardPaymentmakesOldCardGateway's paise method fitPaymentMethod. - Observer:
onPaidlisteners called in a loop. State: eachStatusconstant knows its ownnext(), andSHIPPEDrefuses to move. Facade:placeOrderis one call over all of it. - Seven patterns in about 70 lines is far more than a real feature this size needs; in an interview, use only the ones a requirement asks for.
Look for the tell-tale signs: a class that implements an interface and holds another object of the same interface (Decorator or Proxy), a class that implements our interface but calls a differently named method inside (Adapter), a list of listeners called in a loop (Observer), a static create(String type) (Factory).
Final interview drill: SOLID, patterns and LLD
A final drill puts the whole section into the answers interviewers expect.
For any design question: state the requirement, name the variation, pick the pattern for it, show the interface and two implementations, and say what you would not add.
1. Requirement: "ShopLite will add more payment methods."2. Variation: payment behaviour differs and will grow.3. Pattern: Strategy (PaymentMethod) + a factory to pick one by name.4. Shape: interface PaymentMethod { PaymentResult pay(Order o); } UpiPayment, CardPayment; CheckoutService receives it.5. SOLID: open/closed (new class per method), dependency inversion.6. Not adding: no Singleton or Abstract Factory; nothing asks for them.Practise the answers in the Interview tab out loud, in under a minute each. Short, concrete answers with one ShopLite example beat long lists of definitions.
Order of execution
Answer a design question
Put the steps of a good one-minute design answer in order.
Finish up
Mark complete & continue
Next: Milestone project: ShopLite order engine with patterns