Notes and exercises for learning design patterns
Implement Singleton behavior with a metaclass.
In Exercise 2, the decorator worked, but it replaced the class name with a wrapper function. In this exercise, the class should remain a real class.
That is the advantage of the metaclass approach.
type as their metaclass__call__ on a custom metaclassisinstance(obj, Class) workingA regular class behaves roughly like this:
type.__call__(RegularSettings, "development")
That creates a new object every time.
Your job is to change that call path by defining:
class SingletonMeta(type):
def __call__(cls, *args, **kwargs):
...
Then classes can opt in:
class Settings(metaclass=SingletonMeta):
...
Open exercise3.py.
Fill the TODOs so that:
SingletonMeta return one cached object.__init__ runs only on the first creation.isinstance(obj, Settings) works.python -m pytest exercise3.py