TL;DR: Whats the difference between Dependency Injection and Singleton Pattern if the injected object is a Singleton?
I'm getting mixed results for how to resolve the design problem I am currently facing.
I would like to have a configuration that is application wide so that different objects and alter the configuration.
I thought to resolve this using a Singleton:
class ConfigMeta(type):
_instance = None
def __call__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
class Config(metaclass=ConfigMeta):
def __init__(self) -> None:
pass
But searching has shown this to be prone to errors and considered bad practice (when managing class states). Just about every other post suggests using Dependency Injection, but they confuse me on how they do it. They all state "your implementation can be a Singleton, but inject it into other objects in thier constructors".
That would be something along the lines of:
# foo.py
from config import Config
class Foo:
def __init__(self):
self.config = Config()
# bar.py
from config import Config
class Bar:
def __init__(self):
self.config = Config()
However, each one of those self.config
refers to the same instance. Hence my confusion...
How is this considered Dependency Injection and not Singleton Pattern?
If it is considered Dependency Injection, what would it look like as just Singleton Pattern?
Aucun commentaire:
Enregistrer un commentaire