以下方法 中只有方法4 最好, 其它都有些问题
# -*- encoding=utf-8 -*-
print '----------------------方法1--------------------------'
# 方法1 通过重写__new__方法
from threading import Lock
class SingleClass(object):
lock = Lock()
def __init__(self, value):
self.value = value
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
cls.lock.required()
if not hasattr(cls, '_instance'):
cls._instance = object.__new__(cls, *args)
cls.lock.release()
return cls._instance
one = SingleClass(2)
two = SingleClass(3)
print one is two # True
print one.value, two.value # 3, 3
one.value = 4
print one.value, two.value # 4, 4
print '----------------------方法2--------------------------'
# 方法2 共享属性(所有实例共享同一个状态字典(dict)) 保证不同实例有相同的状态;
class Borg(object):
_state = {}
def __new__(cls, *args, **kw):
ob = super(Borg, cls).__new__(cls, *args)
ob.__dict__ = cls._state
return ob
class SingleClass(Borg):
def __init__(self, value):
self.value = value
one = SingleClass(2)
two = SingleClass(3)
print one is two # False
print two.__dict__ is one.__dict__ # True
print one.value, two.value # 3 3
one.value = 4
print one.value, two.value # 4 4
print '----------------------方法3--------------------------'
# 方法3: 重写__metaclass__(元类)的call方法
class Singleton(type):
def __call__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instance
class SingleClass(object):
__metaclass__ = Singleton
def __init__(self, value):
self.value = value
one = SingleClass(2)
two = SingleClass(3)
print one is two # False
print one.value, two.value # 2 2
one.value = 4
print one.value, two.value # 4 4
print '----------------------方法4--------------------------'
# 方法4: 使用装饰器(decorator)
def singleton(cls):
instances = {}
def _singleton(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return _singleton
@singleton
class SingleClass(object):
def __init__(self, value):
self.value = value
one = SingleClass(2)
two = SingleClass(3)
print one is two # True
print one.value, two.value # 2 2
one.value = 4
print one.value, two.value # 4 4
print '----------------------方法5--------------------------'
# 类简单工厂模式
class Factory(object):
class __SingleClass(object):
def __init__(self, value):
self.value = value
@classmethod
def get_one(cls, *args, **kwargs):
if not hasattr(cls, '_Factory__instance'):
cls.__instance = cls.__SingleClass( *args, **kwargs)
return cls.__instance
one = Factory.get_one(2)
two = Factory.get_one(3)
print one is two # True
print one.value, two.value # 2 2
one.value = 4
print one.value, two.value # 4 4