| 01 | Factory functions and alternative constructors | one class, built from several kinds of input | a from_ classmethod parses the input, then calls cls(…) | CPython datetime, pydantic, pandas | data arrives as text, numbers or dicts | built in: @classmethod passes the subclass |
|---|
| 02 | Factory Method | a procedure in a base class needs an object a subclass should choose | the procedure calls an overridable method that returns the class | Django form views, socketserver | a framework runs the same steps for every user | often a class attribute, or a parameter |
|---|
| 03 | Abstract Factory | several classes must always come from the same family | one class names every product class; swap the class, swap the set | SQLAlchemy dialects, Django database backends | you support several databases or platforms | a class of classes, or a dataclass of callables |
|---|
| 04 | Builder | parts depend on each other or arrive over time | collect the parts in a spec, then build in a fixed order once | requests, SQLAlchemy select() | order matters or parts repeat | keyword arguments cover the simple case |
|---|
| 05 | Prototype | many variations of a configured object, while others hold the original | every changing method clones first and changes the clone | Django QuerySet, SQLAlchemy, copy.replace() | objects are shared and extended in several directions | copy.replace() and __replace__ |
|---|
| 06 | Singleton | everyone must share exactly one object | create it once and give every caller that instance | CPython random, logging | one default generator, logger or settings object | a module attribute: modules run once |
|---|
| 07 | Registry | a name from config or a URL must become a class, plugins included | registrants add names to a dict; a lookup reads it | SQLAlchemy plugins, Flask routes, codecs | kinds are chosen by name and plugins add more | __init_subclass__, a decorator, or entry points |
|---|
| 08 | Lazy initialization | an expensive object that many runs never use | build it on the first read and store it where the next read finds it | NumPy, functools, Django settings | imports, connections or values that are slow to make | cached_property, module __getattr__, lazy import |
|---|
| 09 | Object pool | each new object costs a handshake, a process or a thread | lend idle objects, make one only when none is waiting | urllib3, SQLAlchemy QueuePool, ThreadPoolExecutor | connections or workers you create many times | use the one inside your Session or engine |
|---|
| 10 | Dependency injection | code that builds its own collaborators can’t be tested or reconfigured | take collaborators as parameters; something outside builds them | pytest fixtures, FastAPI Depends | databases, clocks and clients that tests replace | a parameter with a default |
|---|