首頁  >  文章  >  後端開發  >  python如何實作單例模式

python如何實作單例模式

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼原創
2019-06-22 09:28:412564瀏覽

python如何實作單例模式

python如何實作單一範例模式?以下帶給大家七種不同的方法:

一:staticmethod

程式碼如下:

class Singleton(object):
    instance = None
    def __init__(self):
        raise SyntaxError('can not instance, please use get_instance')
    def get_instance():
        if Singleton.instance is None:
            Singleton.instance = object.__new__(Singleton)
        return Singleton.instance
a = Singleton.get_instance()
b = Singleton.get_instance()
print('a id=', id(a))
print('b id=', id(b))

這個方法的重點是在__init__拋出異常,禁止透過類別來實例化,只能透過靜態get_instance函數來取得實例;因為不能透過類別來實例化,所以靜態get_instance函數中可以透過父類別object.__new__來實例化。

二:classmethod

和方法一類似,程式碼:

class Singleton(object):
    instance = None
    def __init__(self):
        raise SyntaxError('can not instance, please use get_instance')
    def get_instance(cls):
        if Singleton.instance is None:
            Singleton.instance = object.__new__(Singleton)
        return Singleton.instance
a = Singleton.get_instance()
b = Singleton.get_instance()
print('a id=', id(a))
print('b id=', id(b))

該方法的重點是在__init__拋出異常,禁止通過類別來實例化,只能透過靜態get_instance函數來取得實例;因為不能透過類別來實例化,所以靜態get_instance函數中可以透過父類別object.__new__來實例化。

三:類別屬性方法

與方法一類似, 程式碼:

class Singleton(object):
    instance = None
    def __init__(self):
        raise SyntaxError('can not instance, please use get_instance')
    def get_instance():
        if Singleton.instance is None:
            Singleton.instance = object.__new__(Singleton)
        return Singleton.instance
a = Singleton.get_instance()
b = Singleton.get_instance()
print(id(a))
print(id(b))

此方法的重點是在__init__拋出例外,禁止透過類別來實例化,只能透過靜態get_instance函數來取得實例;因為不能透過類別來實例化,所以靜態get_instance函數中可以透過父類別object.__new__來實例化。

四:__new__

常見的方法, 程式碼如下:

class Singleton(object):
    instance = None
    def __new__(cls, *args, **kw):
        if not cls.instance:
            # cls.instance = object.__new__(cls, *args)
            cls.instance = super(Singleton, cls).__new__(cls, *args, **kw)
        return cls.instance
a = Singleton()
b = Singleton()
print(id(a))
print(id(b))

相關推薦:《Python影片教學

五:裝飾器

程式碼如下:

def Singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance
class MyClass:
    pass
a = MyClass()
b = MyClass()
c = MyClass()
print(id(a))
print(id(b))
print(id(c))

六:元類別

python2版:

class Singleton(type):
    def __init__(cls, name, bases, dct):
        super(Singleton, cls).__init__(name, bases, dct)
        cls.instance = None
    def __call__(cls, *args):
        if cls.instance is None:
            cls.instance = super(Singleton, cls).__call__(*args)
        return cls.instance
class MyClass(object):
    __metaclass__ = Singleton
a = MyClass()
b = MyClass()
c = MyClass()
print(id(a))
print(id(b))
print(id(c))
print(a is b)
print(a is c)

或:

class Singleton(type):
    def __new__(cls, name, bases, attrs):
        attrs["_instance"] = None
        return super(Singleton, cls).__new__(cls, name, bases, attrs)
    def __call__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instance
class Foo(object):
    __metaclass__ = Singleton
x = Foo()
y = Foo()
print(id(x))
print(id(y))

python3版:

class Singleton(type):
    def __new__(cls, name, bases, attrs):
        attrs['instance'] = None
        return super(Singleton, cls).__new__(cls, name, bases, attrs)
    def __call__(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
        return cls.instance
class Foo(metaclass=Singleton):
    pass
x = Foo()
y = Foo()
print(id(x))
print(id(y))

#七:名字覆蓋

程式碼如下:

class Singleton(object):
    def foo(self):
        print('foo')
    def __call__(self):
        return self
Singleton = Singleton()
Singleton.foo()
a = Singleton()
b = Singleton()
print(id(a))
print(id(b))

以上是python如何實作單例模式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn