What you will learn
- What problem creational patterns solve: decoupling what you create from how.
- Factory, builder and singleton with runnable code.
- The trade-offs, especially the singleton’s.
Why creation needs design
When new ConcreteThing(...) calls are scattered across a codebase, every caller depends on concrete classes and their constructor details. Creational patterns put creation in one place, so callers depend on an interface and creation rules live together.
The code
"""Creational patterns: factory, builder and singleton."""
import threading
from dataclasses import dataclass, field
# --- Factory: callers ask for a kind, not a class -------------------------------
class Shape:
def area(self) -> float:
raise NotImplementedError
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return round(3.14159 * self.r * self.r, 2)
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
SHAPES = {"circle": Circle, "square": Square}
def make_shape(kind: str, size: float) -> Shape:
try:
return SHAPES[kind](size)
except KeyError:
raise ValueError(f"unknown shape {kind!r}") from None
# --- Builder: readable construction of objects with many optional parts ---------
@dataclass(frozen=True)
class HttpRequest:
method: str
url: str
headers: dict = field(default_factory=dict)
body: str = ""
timeout_s: float = 10.0
class RequestBuilder:
def __init__(self, method: str, url: str):
self._method, self._url = method, url
self._headers, self._body, self._timeout = {}, "", 10.0
def header(self, key, value):
self._headers[key] = value
return self
def json(self, body: str):
self._body = body
return self.header("Content-Type", "application/json")
def timeout(self, seconds: float):
if seconds <= 0:
raise ValueError("timeout must be positive")
self._timeout = seconds
return self
def build(self) -> HttpRequest:
return HttpRequest(self._method, self._url, dict(self._headers), self._body, self._timeout)
# --- Singleton: exactly one instance, created lazily and thread-safely ----------
class Config:
_instance = None
_lock = threading.Lock()
def __init__(self):
self.values = {"env": "prod", "max_connections": 50}
@classmethod
def instance(cls) -> "Config":
if cls._instance is None: # fast path without locking
with cls._lock:
if cls._instance is None: # re-check inside the lock
cls._instance = cls()
return cls._instance
if __name__ == "__main__":
print([make_shape(k, 2).area() for k in ("circle", "square")])
req = (RequestBuilder("POST", "https://api.example.com/orders")
.json('{"sku": "A1", "qty": 2}').header("Idempotency-Key", "k-42").timeout(3).build())
print(req)
instances = set()
threads = [threading.Thread(target=lambda: instances.add(id(Config.instance()))) for _ in range(20)]
for t in threads:
t.start()
for t in threads:
t.join()
print("distinct Config instances:", len(instances))
Output:
[12.57, 4]
HttpRequest(method='POST', url='https://api.example.com/orders', headers={'Content-Type': 'application/json', 'Idempotency-Key': 'k-42'}, body='{"sku": "A1", "qty": 2}', timeout_s=3)
distinct Config instances: 1
Factory
make_shape("circle", 2) returns a Shape without the caller importing Circle. A registry dictionary means adding a Triangle is one class plus one dictionary entry, with no if/elif chain to edit (Open/Closed again).
Use a factory when:
- The concrete type is chosen at runtime (from config, user input or a request field).
- Construction has rules you don’t want repeated (validation, defaults, wiring dependencies).
Variants you’ll hear about: factory method (a subclass decides which product to create) and abstract factory (creates families of related objects, like a UIFactory producing matching Button and Checkbox for a theme). In interviews, a simple factory function or class is usually enough.
Builder
HttpRequest has two required fields and several optional ones. Constructors with eight positional parameters are error-prone. The builder:
- Makes each optional part explicit and readable (
.header(...),.timeout(3)). - Validates as it goes (
timeoutmust be positive). - Produces an immutable object (
frozen=True), so a built request can’t be half-modified later.
Use it for objects with many optional parts or multi-step construction: queries, HTTP requests, reports, test fixtures. In Python, keyword arguments with defaults often remove the need; in Java the builder is very common.
Singleton
Config.instance() always returns the same object. The double-checked locking keeps it thread-safe: the outer check avoids taking the lock on every call, and the inner check stops two threads that both passed the outer check from creating two instances. The test starts 20 threads and confirms one instance.
Be careful with singletons:
- They are global state in disguise: hidden dependencies, hard to replace in tests.
- They make parallel tests interfere with each other.
Prefer creating one instance at startup and injecting it where needed. Reach for a true singleton only for things that must be unique per process (a connection pool, a hardware handle) and even then inject it.
Java version of the same lazy, thread-safe idea using the holder idiom:
public final class Config {
private Config() {}
private static class Holder { static final Config INSTANCE = new Config(); }
public static Config getInstance() { return Holder.INSTANCE; } // JVM class loading is thread-safe
}
Key takeaways
- Factories hide concrete classes and centralise construction rules; a registry keeps them open for extension.
- Builders make complex, optional construction readable and can produce immutable objects.
- Singletons are global state; use double-checked locking or a holder idiom if you must, and prefer dependency injection.
Exercises
- Add a
triangleshape to the factory, and make an unknown kind’s error list the valid kinds. - Add a
.query(key, value)method toRequestBuilderthat appends URL query parameters safely. - Rewrite code that uses
Config.instance()inside a function so it receives the config as a parameter. What does that change for testing?
Quiz
- Why is there a second
if cls._instance is Noneinside the lock? - When would you choose a builder over a constructor?
- Name one downside of singletons.
Show answers
- Two threads can both pass the first check before either acquires the lock; the second check stops the second thread from creating another instance.
- When an object has many optional parameters, needs validation during construction, or should be immutable once built.
- Any of: hidden global state, hard to mock in tests, tests interfering with each other, tight coupling.