Python单例模式

重写new方法

# coding=utf-8
class Singleton(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instance


class MyClass(Singleton):
    a = 1


one = MyClass()
two = MyClass()

print(id(one))
print(id(two))

装饰器版本

# coding=utf-8
def singleton(cls, *args, **kw):
    instances = {}

    def getinstance():
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]
    return getinstance


@singleton
class MyClass(object):
    a = 1


one = MyClass()
two = MyClass()

print(id(one))
print(id(two))

import导入

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

my_singleton = My_Singleton()

# to use
from mysingleton import my_singleton

my_singleton.foo()

你可能感兴趣的:(Python单例模式)