- 优点:
- 实例控制
单例模式会阻止其他对象实例化,其自己的单例对象的副本,从而确保所有对象都访问唯一实例
- 灵活性
因为类控制了实例化过程,所以类可以灵活更改实例化过程
- 缺点
- 开销
虽然数量很少,但如果每次对象请求引用时都要检查是否存在类的实例,将仍然需要一些开销.可以通过使用静态初始化解决问题.
- 可能的开发混淆
使用单例对象(尤其在类库中定义的对象)时,开发人员必须记住自己不能使用new关键字实例化对象.因为可能无法访问库源代码.因此应用程序开发人员可能会意外发现自己无法直接实例化此类.
- 对象生存期
不能解决删除单个对象的问题.在提供内存管理的语言中,只有单例类能够导致实例被取消分配,因为它包含对该实例的私有引用.在某些语言中,其他类可以删除对象实例,但这样会导致单例类中出现悬浮引用.
方法1
class singleton:
def __init__(self, aClass):
self.aClass = aClass
self.instance = None
def __call__(self, *args):
if self.instance == None:
self.instance = self.aClass(*args)
return self.instance
@singleton # Person = singleton(Person)
class Person:
def __init__(self, name, hours, rate):
self.name = name
self.hours = hours
self.rate = rate
def pay(self):
return self.hours * self.rate
方法2
def getInstance(aClass, *args):
if aClass not in instances:
instances[aClass] = aClass(*args)
return instances[aClass] # 每一个类只能存在一个实例
def singleton(aClass):
def onCall(*args):
return getInstance(aClass, *args)
return onCall
@singleton # Person = singleton(Person)
class Person:
def __init__(self, name, hours, rate):
self.name = name
self.hours = hours
self.rate = rate
def pay(self):
return self.hours * self.rate
方法3
class Singleton(object):
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **kw)
return cls._instance
class MyClass(Singleton):
a = 1
方法4
class Borg(object):
_state = {}
def __new__(cls, *args, **kw):
ob = super(Borg, cls).__new__(cls, *args, **kw)
ob.__dict__ = cls._state
return ob
class MyClass2(Borg):
a = 1
方法5
class Singleton2(type):
def __init__(cls, name, bases, dict):
super(Singleton2, cls).__init__(name, bases, dict)
cls._instance = None
def __call__(cls, *args, **kw):
if cls._instance is None:
cls._instance = super(Singleton2, cls).__call__(*args, **kw)
return cls._instance
class MyClass3(object):
__metaclass__ = Singleton2
方法6
def singleton(cls, *args, **kw):
instances = {}
def _singleton():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return _singleton
@singleton
class MyClass4(object):
a = 1
def __init__(self, x=0):
self.x = x