Singleton
medium 60 minOne object and one way to reach it.
Watch lesson4:52
Scopes and when not
Single, request, tenant, thread: what a container does for you.
The point: "one" is a scope. A container lets you say one per what, in one place, and reports when scopes do not fit.
Scopes
One per what?
| Scope | Example | Danger |
|---|---|---|
| Process or container | Pool, settings, thread pool | Grows state that belongs to one user |
| Tenant or database (multiton) | A pool per customer database | Never removed: 500 tenants, 500 pools |
| Request | Cart, user, transaction | Escapes into a longer living object |
| Thread | A formatter that is not thread safe | In a thread pool the next request finds the old value |
| None, new each time | Values, builders | Costly objects are rebuilt |
import threadingclass Container: """One per container, one per request, or a new one each time.""" def __init__(self): self._recipes, self._singles, self._lock = {}, {}, threading.RLock() def register(self, name, create, scope="single"): self._recipes[name] = (create, scope) def open_request(self): return Request(self) def _make(self, name, request): create, scope = self._recipes[name] if scope == "single": with self._lock: if name not in self._singles: self._singles[name] = create(Request(self, root=True)) return self._singles[name] if scope == "request": if request.root: raise LookupError(f"a single may not hold the request object {name}") if name not in request.made: request.made[name] = create(request) return request.made[name] return create(request)class Request: def __init__(self, container, root=False): self.container, self.root, self.made = container, root, {} def get(self, name): return self.container._make(name, self)c = Container()c.register("pool", lambda r: object())c.register("cart", lambda r: [], scope="request")asha, lee = c.open_request(), c.open_request()print("one pool:", asha.get("pool") is lee.get("pool"))print("own cart:", asha.get("cart") is not lee.get("cart"))c.register("bad", lambda r: r.get("cart"))try: asha.get("bad")except LookupError as error: print(error)Spring says it in its documentation: the Singleton of the book hard-codes one instance per class loader, while a singleton bean means one per container and per bean definition. The class stays ordinary. That is the difference between a class that forbids and a place that decides.
Two ways to reach the one object
1/2Locator
The class asks a global object for what it needs. This is the Singleton with one more step: the need is still hidden, and a missing entry shows at run time.
usesdepends on
How to get rid of one in a large program
| Step | Change | Can be released |
|---|---|---|
| 1 | Extract an interface with the methods that are used | Yes |
| 2 | Give each class a constructor parameter whose default is getInstance() | Yes, nobody breaks |
| 3 | Tests pass their own object | Yes |
| 4 | Move callers to pass it, from main downwards | Class by class |
| 5 | Remove the default, then the static method | When the search finds no caller |
Honest uses that remain
- A value without state, such as an empty object or a null object
- Library internals that users must not have to wire
- A registry that the language itself keeps, such as loggers by name
- Very small programs
Signs that it is being misused
- A
reset()that only tests call - Tests that must not run in parallel
getInstance()in a domain class such as Order- A setter that production code calls from many places