AlgoViz

Singleton

medium 60 min

One 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?

ScopeExampleDanger
Process or containerPool, settings, thread poolGrows state that belongs to one user
Tenant or database (multiton)A pool per customer databaseNever removed: 500 tenants, 500 pools
RequestCart, user, transactionEscapes into a longer living object
ThreadA formatter that is not thread safeIn a thread pool the next request finds the old value
None, new each timeValues, buildersCostly objects are rebuilt
Python
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)
A small container. It refuses the classic mistake: a long living object that holds the object of one request.
Edit and run it in your browser

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

asksfindsCheckout, asking+ page()Locator+ get(name): Object«interface»Settings+ databaseUrl()+ isEnabled(flag)

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

The test: can you use Checkout in a unit test without starting anything? In the upper row you must fill the locator first.

How to get rid of one in a large program

StepChangeCan be released
1Extract an interface with the methods that are usedYes
2Give each class a constructor parameter whose default is getInstance()Yes, nobody breaks
3Tests pass their own objectYes
4Move callers to pass it, from main downwardsClass by class
5Remove the default, then the static methodWhen the search finds no caller
Step 2 is the trick. It makes the change small, and the program works after every step.

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