3 ms·
It's basically a global / hoist with a more ergonomic way of accessing the state. Instead of a get_global_state() style function, you just have the Borg constru
by kortex 4y ago
It's basically a global / hoist with a more ergonomic way of accessing the state. Instead of a get_global_state() style function, you just have the Borg constructor.
Personally I'm a fan of dependency injection whenever possible. But borg pattern has gotten me out of a pinch (exactly) once.
- sillysaurusx 4y agoWhy not just make a global though?
- kortex 4y agoMy understanding is that Borgs can be subclassed, you can modify the behavior, use descriptors (setters/getters), etc. You also avoid the `global` keyword. It's really not the most compelling reason. I recently found a cleaner way that actually achieves identity-equality, which I think is a much better way of going about things. Not actually using it anywhere at the moment, but I think it's neat. class Singleton(type): def __init__(cls, name, bases, dict): super(Singleton, cls).__init__(name, bases, dict) cls.instance = None def __call__(cls, *args, **kw): if cls.instance is None: cls.instance = super(Singleton, cls).__call__(*args, **kw) return cls.instance class MyClass(metaclass=Singleton): ... class MySubclass(MyClass): ... >>> MyClass() is MyClass() True >>> MySubclass() is MySubclass() True >>> MySubclass() is MyClass() False
- sillysaurusx 4y agoThank you for this. I love that you have little patterns in the back of your mind that you might use, but haven't yet. Any others like that? An opportunity to ask someone about that is pretty rare.