Creational patterns practice
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.
ShopLite's code grew messy in five ways: shared objects, hard-wired classes, mismatched families, long constructors and copied set-up. This optional checkpoint helps you pick the right fix for each.
Choosing a creational pattern
Start from the problem, not the pattern. Ask what is hard about creating this object, then use the example below to see all five patterns working in one small order.
Example 1 · All the creational patterns in one small order
import java.util.ArrayList;import java.util.List;
enum AppConfig { INSTANCE;
double freeDeliveryFrom() { return 499; }}
interface PaymentMethod { String pay(double amount);}
class UpiPayment implements PaymentMethod { public String pay(double amount) { return String.format("UPI Rs %.2f", amount); }}
class CardPayment implements PaymentMethod { public String pay(double amount) { return String.format("card Rs %.2f", amount); }}
class PaymentFactory { // Factory: one place picks the class static PaymentMethod create(String type) { return switch (type) { case "UPI" -> new UpiPayment(); case "CARD" -> new CardPayment(); default -> throw new IllegalArgumentException("Unknown payment type: " + type); }; }}
class CartTemplate { private final List<String> items; private double total;
CartTemplate(List<String> items, double total) { this.items = new ArrayList<>(items); this.total = total; }
CartTemplate copy() { return new CartTemplate(items, total); }
void add(String item, double price) { items.add(item); total += price; }
List<String> items() { return List.copyOf(items); } double total() { return total; }}
final class Receipt { // Builder: many fields, checked once private final String orderId; private final List<String> items; private final double subtotal; private final double deliveryFee; private final String payment;
private Receipt(Builder b) { orderId = b.orderId; items = List.copyOf(b.items); subtotal = b.subtotal; deliveryFee = b.deliveryFee; payment = b.payment; }
@Override public String toString() { return String.format("%s | %s | subtotal Rs %.2f | delivery Rs %.2f | %s", orderId, items, subtotal, deliveryFee, payment); }
static final class Builder { private String orderId; private List<String> items = List.of(); private double subtotal; private double deliveryFee; private String payment;
Builder orderId(String id) { this.orderId = id; return this; } Builder items(List<String> items) { this.items = items; return this; } Builder subtotal(double s) { this.subtotal = s; return this; } Builder deliveryFee(double d) { this.deliveryFee = d; return this; } Builder payment(String p) { this.payment = p; return this; }
Receipt build() { if (orderId == null || items.isEmpty() || payment == null) { throw new IllegalStateException("orderId, items and payment are required"); } return new Receipt(this); } }}
public class CreationalTourDemo { public static void main(String[] args) { CartTemplate examKit = new CartTemplate(List.of("Pens x10", "Scale", "Calculator"), 420); CartTemplate cart = examKit.copy(); cart.add("Highlighter", 60);
double delivery = cart.total() >= AppConfig.INSTANCE.freeDeliveryFrom() ? 0 : 40; PaymentMethod payment = PaymentFactory.create("UPI");
Receipt receipt = new Receipt.Builder() .orderId("ORD-501") .items(cart.items()) .subtotal(cart.total()) .deliveryFee(delivery) .payment(payment.pay(cart.total() + delivery)) .build(); System.out.println(receipt); System.out.println("Template unchanged: " + examKit.items()); }}ORD-501 | [Pens x10, Scale, Calculator, Highlighter] | subtotal Rs 480.00 | delivery Rs 40.00 | UPI Rs 520.00 Template unchanged: [Pens x10, Scale, Calculator]
What this code does
- Each pattern sits where its problem is: one config (Singleton), a payment class picked by key (Factory), a copied cart template (Prototype) and a receipt with many fields (Builder).
- The cart total is Rs 480, below the Rs 499 limit from
AppConfig, so Rs 40 delivery is added and UPI is charged Rs 520.
Match the problem to the pattern:
- Exactly one shared instance (config, id generator): Singleton, or a singleton-scoped Spring bean.
- The class depends on a key or setting and callers should not name it: simple factory or Factory Method.
- Several objects must match as a family (region tax, currency, shipping): Abstract Factory.
- Many fields, several optional, easy-to-swap arguments: Builder.
- Set-up is expensive and many near-copies are needed: Prototype with a copy constructor.
One program often uses several, as the example above shows.
Mistake 1: a lazy singleton that is not thread-safe
A lazy if (instance == null) instance = new X(); lets two threads create two instances. It passes single-threaded tests and fails under load.
Example 2 · Fixing a lazy singleton with the holder idiom
import java.util.ArrayList;import java.util.List;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicInteger;
// Was: private static GstRateTable instance; ... if (instance == null) instance = new GstRateTable();class GstRateTable { static final AtomicInteger created = new AtomicInteger();
private GstRateTable() { created.incrementAndGet(); }
private static class Holder { static final GstRateTable INSTANCE = new GstRateTable(); }
static GstRateTable getInstance() { return Holder.INSTANCE; }
double rateFor(String category) { return category.equals("Books") ? 0.0 : 0.18; }}
public class HolderFixDemo { public static void main(String[] args) throws InterruptedException { Set<GstRateTable> seen = ConcurrentHashMap.newKeySet(); List<Thread> threads = new ArrayList<>(); for (int i = 0; i < 8; i++) threads.add(new Thread(() -> seen.add(GstRateTable.getInstance()))); for (Thread t : threads) t.start(); for (Thread t : threads) t.join();
System.out.println("Instances created: " + GstRateTable.created.get()); System.out.println("Distinct objects seen: " + seen.size()); System.out.println("GST on Clothing: " + GstRateTable.getInstance().rateFor("Clothing")); }}Instances created: 1 Distinct objects seen: 1 GST on Clothing: 0.18
What this code does
- Eight threads asked for the table at once, and the JVM still created exactly one, because
Holderis initialised only once. - Calls to
getInstance()take no lock at all, so the fix costs nothing after the first call.
The smallest safe fix is the holder idiom: move the instance into a private static nested class and return Holder.INSTANCE. It stays lazy and needs no locks. Alternatives are synchronized getInstance(), an enum, or double-checked locking with volatile.
Predict the output
Why the bug hides
Read the code and pick the output.
One thread calls the lazy singleton three times.
Mistake 2: telescoping constructors
Five constructors that pass defaults down, and calls like new ProductListing("Backpack", 1299, null, null, 70), mean nobody can read the call and invalid values slip through.
Example 3 · From telescoping constructors to a validating builder
final class DeliveryRequest { private final String orderId; private final String pin; private final String slot; private final boolean express; private final boolean fragile; private final String instructions;
private DeliveryRequest(Builder b) { orderId = b.orderId; pin = b.pin; slot = b.slot; express = b.express; fragile = b.fragile; instructions = b.instructions; }
static Builder builder(String orderId, String pin) { // required fields up front return new Builder(orderId, pin); }
@Override public String toString() { return orderId + " to " + pin + ", slot " + slot + (express ? ", express" : "") + (fragile ? ", fragile" : "") + (instructions.isEmpty() ? "" : ", note: " + instructions); }
static final class Builder { private final String orderId; private final String pin; private String slot = "ANY"; private boolean express; private boolean fragile; private String instructions = "";
private Builder(String orderId, String pin) { this.orderId = orderId; this.pin = pin; }
Builder slot(String slot) { this.slot = slot; return this; } Builder express() { this.express = true; return this; } Builder fragile() { this.fragile = true; return this; } Builder instructions(String text) { this.instructions = text; return this; }
DeliveryRequest build() { if (!pin.matches("\\d{6}")) throw new IllegalStateException("PIN must be 6 digits"); if (express && slot.equals("ANY")) throw new IllegalStateException("express delivery needs a slot"); return new DeliveryRequest(this); } }}
public class DeliveryBuilderDemo { public static void main(String[] args) { System.out.println(DeliveryRequest.builder("ORD-601", "411001").build()); System.out.println(DeliveryRequest.builder("ORD-602", "560001") .slot("6-9 PM").express().fragile().instructions("Call before coming").build()); try { DeliveryRequest.builder("ORD-603", "560001").express().build(); } catch (IllegalStateException e) { System.out.println("Rejected: " + e.getMessage()); } }}ORD-601 to 411001, slot ANY ORD-602 to 560001, slot 6-9 PM, express, fragile, note: Call before coming Rejected: express delivery needs a slot
What this code does
- The two required values go into
builder(orderId, pin), so the compiler forces them; every optional value has a name and a default. build()checks a rule that involves two fields, express and slot, which no single setter could check.
Convert in three steps: put required fields in the builder's constructor (or check them in build()), give each optional field a named fluent method with a default, and move every rule into build(). Make the object's constructor private so the old calls cannot come back.
Mistake 3: scattered new calls
When checkout and the seller dashboard each pick a shipping class with their own if and new, a new type must be added in both, and an unknown type quietly becomes "standard".
Example 4 · Scattered new calls replaced by one factory
interface NotificationService { void send(String to, String text);}
class EmailNotification implements NotificationService { public void send(String to, String text) { System.out.println("Email to " + to + ": " + text); }}
class SmsNotification implements NotificationService { public void send(String to, String text) { System.out.println("SMS to " + to + ": " + text); }}
class WhatsAppNotification implements NotificationService { public void send(String to, String text) { System.out.println("WhatsApp to " + to + ": " + text); }}
class NotificationFactory { static NotificationService create(String channel) { return switch (channel) { case "EMAIL" -> new EmailNotification(); case "SMS" -> new SmsNotification(); case "WHATSAPP" -> new WhatsAppNotification(); default -> throw new IllegalArgumentException("Unknown channel: " + channel); }; }}
// Both services used to contain their own if/else with new ...Notification()class OrderService { void confirm(String channel, String to, String orderId) { NotificationFactory.create(channel).send(to, orderId + " confirmed"); }}
class ReturnsService { void bookPickup(String channel, String to, String orderId) { NotificationFactory.create(channel).send(to, "Pickup booked for " + orderId); }}
public class ScatteredToFactoryDemo { public static void main(String[] args) { new OrderService().confirm("EMAIL", "asha@mail.com", "ORD-701"); new ReturnsService().bookPickup("WHATSAPP", "9876543210", "ORD-702"); try { new OrderService().confirm("FAX", "0201234567", "ORD-703"); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } }}Email to asha@mail.com: ORD-701 confirmed WhatsApp to 9876543210: Pickup booked for ORD-702 Unknown channel: FAX
What this code does
OrderServiceandReturnsServiceno longer name any notification class; both ask the factory.- An unknown channel now fails loudly with its name, instead of silently falling back to email.
Move the choice into one factory method that returns the interface type and throws for unknown keys. Callers become one line each, and a new type is one class plus one case.
Find the bug
Find the scattered choice
Each snippet has one wrong line. Tap it, then check the fix.
Which line copies the choice of class that a factory should own?
Round 1 of 2Interview drill: which singleton is best?
A strong answer names a winner for each context and the reason:
- Plain Java: an enum singleton, because the JVM makes it thread-safe and protects it from reflection and serialization.
- Plain Java, needs laziness or a parent class: the holder idiom.
- Spring Boot: no hand-made singleton at all; a normal class as a singleton-scoped bean, injected through constructors, so tests can still create their own instance.
Finish with the cost: any singleton is global state, so keep it read-only and inject it rather than calling getInstance() all over the code.
Finish up
Mark complete & continue
Next: Project: ShopLite payments and order creation