Python 单例模式

单例模式

1. 使用 __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)
        return cls._instance


class MyClass(Singleton):
    pass

2. 装饰器版本


def singleton(cls, *args, **kwargs):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return getinstance


@singleton
class MyClass(object):
    pass

3. import 方法

作为Python的模块是天然的单例模式:


# mysingleton.py
class MySingleton(object):
    def foo(self):
        pass

my_singleton = MySingleton()

# to use
from mysingleton import my_singleton

my_singleton.foo()