Singleton: Define the Scope of One
Singleton restricts a class to one instance within a defined scope and provides an access point. First ask what scope ‘one’ refers to. One object in a process is different from one object across several servers.
A simple single-process example
class Settings:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.debug = False
return cls._instance
a = Settings()
b = Settings()
a.debug = True
print(a is b)
print(b.debug)
The outputs are True and True. Both calls return the same object, so a change through a is visible through b. This shortened example is for single-threaded understanding; it does not solve concurrent creation, inheritance, or serialization concerns.
Convenient access has costs
Globally shared mutable state hides dependencies. Settings left by one test can affect another. Initialization order and cleanup also need clear ownership.
A shared object does not always require enforced Singleton. Constructing it once at program startup and passing it where needed makes scope visible and supports replacement during tests. Cross-process consistency requires a database or another coordination mechanism.
Check your understanding
If four server processes run, does this class guarantee one object across the entire service?
Show explanation
No. Processes have separate memory and can each hold an instance. Singleton does not automatically provide distributed single execution or data consistency.