Python单体模式的几种常见实现方法详解

yipeiwu_com5年前Python基础

本文实例讲述了Python单体模式的几种常见实现方法。分享给大家供大家参考,具体如下:

这里python实现的单体模式,参考了:https://stackoverflow.com/questions/1363839/python-singleton-object-instantiation/1363852

一、修改父类的 __dict__

class Borg:
  _shared_state = {}
  def __init__(self):
    self.__dict__ = self._shared_state
class Singleton(Borg):
  def __init__(self, name):
    super().__init__()
    self.name = name
  def __str__(self):
    return self.name
x = Singleton('sausage')
print(x)
y = Singleton('eggs')
print(y)
z = Singleton('spam')
print(z)
print(x)
print(y)

注意,这种方法实现的并非真正的单体模式!!

下面几种方法实现的才是真正的单体模式

二、使用元类

先看看这里关于元类的描述:

元类一般用于创建类。

在执行类定义时,解释器必须要知道这个类的正确的元类。解释器会先寻找类属性__metaclass__,如果此属性存在,就将这个属性赋值给此类作为它的元类。如果此属性没有定义,它会向上查找父类中的__metaclass__。如果还没有发现__metaclass__属性,解释器会检查名字为__metaclass__的全局变量,如果它存在,就使用它作为元类。否则, 使用内置的 type 作为此类的元类。

1. 继承 type,使用 __call__

注意__call__的参数

class Singleton(type):
  _instance = None
  def __call__(self, *args, **kw):
    if self._instance is None:
      self._instance = super().__call__(*args, **kw)
    return self._instance
class MyClass(object):
  __metaclass__ = Singleton
print(MyClass())
print(MyClass())

2. 继承 type,使用 __new__

注意__new__的参数

class Singleton(type):
  _instance = None
  def __new__(cls, name, bases, dct):
    if cls._instance is None:
      cls._instance = super().__new__(cls, name, bases, dct)
    return cls._instance
class MyClass(object):
  __metaclass__ = Singleton
print(MyClass())
print(MyClass())

3. 继承 object,使用 __new__

注意__new__的参数

class Singleton(object):
  _instance = None
  def __new__(cls):
    if cls._instance is None:
      cls._instance = super().__new__(cls)
    return cls._instance
class MyClass(object):
  __metaclass__ = Singleton
print(MyClass())
print(MyClass())

下面还有一个很巧妙的方法实现单体模式

使用类方法classmethod

class Singleton:
  _instance = None
  @classmethod
  def create(cls):
    if cls._instance is None:
      cls._instance = cls()
    return cls._instance
  def __init__(self):
    self.x = 5    # or whatever you want to do
sing = Singleton.create()
print(sing.x) # 5
sec = Singleton.create()
print(sec.x) # 5

更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python 删除整个文本中的空格,并实现按行显示

希望以后每天写一篇博客,总结一下每天用到的基本功能,不然项目做完也就做完了,给自己留下的资料太少了。 今天需要造大量的姓名和家庭住址的数据,因此根据读取文件中现有的lastname、fi...

Python数据可视化库seaborn的使用总结

Python数据可视化库seaborn的使用总结

seaborn是python中的一个非常强大的数据可视化库,它集成了matplotlib,下图为seaborn的官网,如果遇到疑惑的地方可以到官网查看。http://seaborn.py...

Python 开发Activex组件方法

使用win32com模块开发window ActiveX的示例:(如果你还没有装win32com模块的话,请到http://python.net/crew/skippy/win32/Do...

深入讲解Python编程中的字符串

深入讲解Python编程中的字符串

Python转义字符 在需要在字符中使用特殊字符时,python用反斜杠(\)转义字符。如下表: Python字符串运算符 下表实例变量a值为字符串"Hello",b变量值为"Pyt...

python引入导入自定义模块和外部文件的实例

项目中想使用以前的代码,或者什么样的需求致使你需要导入外部的包 如果是web 下,比如说django ,那么你新建一个app,把你需要导入的说用东东,都写到这个app中,然后在setti...