Python设计模式之单例模式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python设计模式之单例模式相关的知识,希望对你有一定的参考价值。
单例模式
module
class Singleton(object):
def __init__(self):
self._val = 10
@property
def val(self):
return self._val
@val.setter
def val(self, val):
self._val = val
singleton = Singleton()
from Singleton import singleton
assert singleton.val == 10
singleton.val = 20
assert singleton.val == 20
metaclass
class Singleton(type):
def __init__(cls, what, bases, dict):
super().__init__(what, bases, dict)
cls._instance = None
def __call__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
class MyClass(metaclass=Singleton):
pass
class1 = MyClass()
class2 = MyClass()
assert class1 == class2
__call__
class Singleton(object):
_instance = None
def __new__(cls, *more):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *more)
return cls._instance
class MyClass(Singleton):
pass
class1 = MyClass()
class2 = MyClass()
assert id(class1) == id(class2)
装饰器
import functools
def singleton(cls):
cls.__new_original__ = cls.__new__
@functools.wraps(cls.__new__)
def singleton_new(cls, *args, **kw):
it = cls.__dict__.get(‘__it__‘)
if it is not None:
return it
cls.__it__ = it = cls.__new_original__(cls, *args, **kw)
it.__init_original__(*args, **kw)
return it
cls.__new__ = singleton_new
cls.__init_original__ = cls.__init__
cls.__init__ = object.__init__
return cls
@singleton
class myclass:
pass
class1 = myclass()
class2 = myclass()
assert class1 == class2
以上是关于Python设计模式之单例模式的主要内容,如果未能解决你的问题,请参考以下文章