单例模式
Python 单例模式
Method 1: A decorator
1 | def singleton(class_): |
Pros
- Decorators are additive in a way that is often more intuitive than multiple inheritance.
Cons
- While objects created using MyClass() would be true singleton objects, MyClass itself is a a function, not a class, so you cannot call class methods from it. Also for
m = MyClass(); n = MyClass(); o = type(n)();
thenm == n && m != o && n !=
Method 2: A base class
1 | class Singleton(object): |
Pros
- It’s a true class
Cons
- Multiple inheritance - eugh!
__new__
could be overwritten during inheritance from a second base class? One has to think more than is necessa
Method 3: A metaclass
1 | class Singleton(type): |
pros
- It’s a true class
- Auto-magically covers inheritance
- Uses
__metaclass__
for its proper purpose (and made me aware of it)
Cons
- Are there any?
<!–stackedit_data:
eyJoaXN0b3J5IjpbLTEwOTI4MDMzMTBdfQ== - ->