Notes and exercises for learning design patterns
Turn Singleton behavior into a reusable decorator.
In Exercise 1, the singleton logic was written directly inside AppSettings. That works, but the same _instance and __new__ logic would be repeated if another class also needed Singleton behavior.
In this exercise, you will move the Singleton behavior into a decorator:
@singleton
class MetricsRegistry:
...
reset_instance() helper for exercises and testsOpen exercise2.py.
Fill the TODOs in singleton(cls) so that:
reset_instance() clears the cached instance.metrics1 = MetricsRegistry(namespace="billing")
metrics2 = MetricsRegistry(namespace="email")
assert metrics1 is metrics2
assert metrics2.namespace == "billing"
The first call wins because the second call returns the cached object.
python -m pytest exercise2.py