{}DSA Atlas

Creational Patterns

Singleton (and its thread-safe implementations and pitfalls), Factory Method, Simple Factory and registries, Abstract Factory, Builder, Prototype and Object Pool — with intent, structure, Java/Python code and when not to use them.

Intermediate4 interview questions

Overview

PatternIntentTypical use
Singletonexactly one instance, global accessconfig, registry (prefer DI)
Simple factory / Factory Methodcentralise creation of one product typenotifiers, parsers, payment methods
Abstract Factorycreate families of related objectscross-platform UI, cloud provider SDKs
Builderconstruct complex objects step by steprequests, configs, immutable objects with many fields
Prototypeclone preconfigured objectstemplates, expensive-to-build objects
Object Poolreuse expensive objectsDB connections, threads, buffers

Singleton

// 1. Enum — simplest correct singleton
public enum AppConfig {
    INSTANCE;
    private final Properties props = load();
    public String get(String key) { return props.getProperty(key); }
    private static Properties load() { /* read file */ return new Properties(); }
}

// 2. Holder idiom — lazy, thread-safe, no synchronization cost
public final class IdGenerator {
    private IdGenerator() {}
    private static final class Holder { static final IdGenerator INSTANCE = new IdGenerator(); }
    public static IdGenerator getInstance() { return Holder.INSTANCE; }
}

// 3. Double-checked locking — needs volatile!
public final class Registry {
    private static volatile Registry instance;
    private Registry() {}
    public static Registry getInstance() {
        Registry r = instance;
        if (r == null) {
            synchronized (Registry.class) {
                r = instance;
                if (r == null) instance = r = new Registry();
            }
        }
        return r;
    }
}
# Python: a module is already a singleton; if you must:
import threading

class Registry:
    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
        return cls._instance

Factory Method / Simple Factory

interface Notifier { void send(String to, String message); }
class EmailNotifier implements Notifier { public void send(String to, String m) { /* SMTP */ } }
class SmsNotifier implements Notifier { public void send(String to, String m) { /* SMS gateway */ } }
class PushNotifier implements Notifier { public void send(String to, String m) { /* FCM/APNs */ } }

enum Channel { EMAIL, SMS, PUSH }

final class NotifierFactory {
    private static final Map<Channel, Supplier<Notifier>> REGISTRY = Map.of(
        Channel.EMAIL, EmailNotifier::new,
        Channel.SMS, SmsNotifier::new,
        Channel.PUSH, PushNotifier::new);

    static Notifier create(Channel c) {
        Supplier<Notifier> s = REGISTRY.get(c);
        if (s == null) throw new IllegalArgumentException("unsupported channel " + c);
        return s.get();
    }
}
from typing import Callable, Protocol

class Notifier(Protocol):
    def send(self, to: str, message: str) -> None: ...

_registry: dict[str, Callable[[], Notifier]] = {}

def register(channel: str):
    def deco(cls):
        _registry[channel] = cls
        return cls
    return deco

@register("email")
class EmailNotifier:
    def send(self, to, message): ...

@register("sms")
class SmsNotifier:
    def send(self, to, message): ...

def create_notifier(channel: str) -> Notifier:
    return _registry[channel]()            # new channels register themselves (open/closed)

The classic GoF Factory Method puts the creation in an overridable method of a creator class:

Java
abstract class Dialog {
    void render() { Button b = createButton(); b.onClick(this::close); b.draw(); }
    protected abstract Button createButton();          // factory method
    void close() {}
}
class WebDialog extends Dialog { protected Button createButton() { return new HtmlButton(); } }
class AndroidDialog extends Dialog { protected Button createButton() { return new MaterialButton(); } }

Abstract Factory

«interface» CloudFactorystorage() · queue() · kms() AwsFactory GcpFactory S3 SQS AWS KMS GCS Pub/Sub Cloud KMS
Swap one factory to swap a whole consistent family of implementations.
Java
interface BlobStore { void put(String key, byte[] data); }
interface MessageQueue { void publish(String topic, String msg); }

interface CloudFactory {
    BlobStore blobStore();
    MessageQueue queue();
}

class AwsFactory implements CloudFactory {
    public BlobStore blobStore() { return new S3BlobStore(); }
    public MessageQueue queue() { return new SqsQueue(); }
}
class GcpFactory implements CloudFactory {
    public BlobStore blobStore() { return new GcsBlobStore(); }
    public MessageQueue queue() { return new PubSubQueue(); }
}

// client code depends only on the abstractions
class ReportJob {
    private final BlobStore store; private final MessageQueue queue;
    ReportJob(CloudFactory f) { this.store = f.blobStore(); this.queue = f.queue(); }
}

Builder

public final class HttpRequest {
    private final String method, url;
    private final Map<String, String> headers;
    private final byte[] body;
    private final Duration timeout;

    private HttpRequest(Builder b) {
        this.method = b.method; this.url = b.url; this.headers = Map.copyOf(b.headers);
        this.body = b.body; this.timeout = b.timeout;
    }

    public static Builder newBuilder(String url) { return new Builder(url); }

    public static final class Builder {
        private final String url;
        private String method = "GET";
        private final Map<String, String> headers = new HashMap<>();
        private byte[] body = new byte[0];
        private Duration timeout = Duration.ofSeconds(10);

        private Builder(String url) { this.url = Objects.requireNonNull(url); }
        public Builder method(String m) { this.method = m; return this; }
        public Builder header(String k, String v) { headers.put(k, v); return this; }
        public Builder body(byte[] b) { this.body = b; return this; }
        public Builder timeout(Duration t) { this.timeout = t; return this; }

        public HttpRequest build() {
            if (method.equals("GET") && body.length > 0) throw new IllegalStateException("GET with body");
            return new HttpRequest(this);
        }
    }
}

// usage
HttpRequest req = HttpRequest.newBuilder("https://api.example.com/orders")
    .method("POST").header("Content-Type", "application/json")
    .body("{\"sku\":\"A1\"}".getBytes()).timeout(Duration.ofSeconds(3))
    .build();
# Python usually doesn't need a builder: keyword args + frozen dataclass
from dataclasses import dataclass, field

@dataclass(frozen=True)
class HttpRequest:
    url: str
    method: str = "GET"
    headers: dict = field(default_factory=dict)
    body: bytes = b""
    timeout_s: float = 10.0

req = HttpRequest("https://api.example.com/orders", method="POST", body=b'{"sku":"A1"}', timeout_s=3)

Prototype

Java
class Document implements Copyable<Document> {
    private String title;
    private final List<String> sections;
    private final Style style;                       // immutable → safe to share

    Document(Document other) {                       // copy constructor = prototype
        this.title = other.title;
        this.sections = new ArrayList<>(other.sections);   // deep-copy mutable parts
        this.style = other.style;
    }
    public Document copy() { return new Document(this); }
}

Document invoiceTemplate = loadTemplate("invoice");   // expensive once
Document inv = invoiceTemplate.copy();                // cheap per use

Object Pool

Reuse objects that are expensive to create and limited in number:

Java
class ConnectionPool {
    private final BlockingQueue<Connection> idle;
    ConnectionPool(int size, Supplier<Connection> factory) {
        idle = new ArrayBlockingQueue<>(size);
        for (int i = 0; i < size; i++) idle.add(factory.get());
    }
    Connection borrow(Duration timeout) throws InterruptedException {
        Connection c = idle.poll(timeout.toMillis(), TimeUnit.MILLISECONDS);
        if (c == null) throw new IllegalStateException("pool exhausted");   // backpressure
        return c;
    }
    void release(Connection c) { idle.offer(c); }
}

In practice use battle-tested pools (HikariCP, pgbouncer, ThreadPoolExecutor), with validation of borrowed objects, max lifetime and leak detection.

When not to use creational patterns

  • A plain constructor is fine for simple objects — don't build factories "just in case".
  • Python/Kotlin/TypeScript named/default arguments remove most builder needs.
  • Dependency injection replaces most singletons.

Interview questions

0 / 4 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.