单例模式

单例模式

  • __ new _ _方法
class Singleton(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            orig = super(Singleton, cls)
            cls._instance = orig.__new__(cls, *args, **kwargs)
        rerurn cls._instance

class A(Singleton):
    pass

# 类A即为单例类
  • 共享属性
# 创建实例时把所有实例的__dict__指向同一个字典,这样它们都具有相同的属性和方法(类的__dict__存储对象属性)
class Singleton(object):
    _state = {}
    def __new__(cls, *args, **kwargs):
        ob = super(Singleton,cls).__new__(cls, *args, **kwargs)
        ob.__dict__ = cls._state
    return ob
class B(Singleton):
    pass
# 类B即为单例类
  • 装饰器
def singleton(cls):
    instance = {}
    def wapper():
        if cls not in instance:
            instance[cls] = cls(*args, **kwargs)
        return instance[cls]
    return wapper
@singleton
class C:
    pass
# 类C即为单例类
  • import
# 作为Python模块时是天然的单例模式
#创建一个sington.py文件,内容如下:
    class Singleton(object):
        def foo(self):
            pass
    mysington = Singleton()

# 运用
from sington import mysington
mysington.foo()
上一篇:装饰器和单例模式


下一篇:【问题描述】调试基于ACCESS+ASP的网站程序的时候,遇到如下错误:ODCB