单例模式是常见的一种设计模式,它是针对类的一种描述,因此,我们可以使用python的decorator来实现通用的单例模式。

一.基本的单例模式

首先建立我们的decorator。我们需要为classType建立_instance和_lock成员:

Python

def singleton(classType):

classType._instance = None

classType._lock = Lock()

return classType

1

2

3

4

defsingleton(classType):

classType._instance=None

classType._lock=Lock()

returnclassType

然后为class建立getInstance函数:

Python

def __getInstance(classname):

if classname._instance is None:

classname._lock.acquire()

if classname._instance is None:

classname._instance = classname()

classname._lock.release()

return classname._instance

1

2

3

4

5

6

7

def__getInstance(classname):

ifclassname._instanceisNone:

classname._lock.acquire()

ifclassname._instanceisNone:

classname._instance=classname()

classname._lock.release()

returnclassname._instance

然后在我们的decorator中,将getInstance函数添加到class上:

Python

classType.getInstance = classmethod(__getInstance)

1

classType.getInstance=classmethod(__getInstance)

现在我们的代码长这样。这个decorator已经具备了基本功能:

Python

def __getInstance(classType):

if classType._instance is None:

classType._lock.acquire()

if classType._instance is None:

classType._instance = classType()

classType._lock.release()

return classType._instance

def singleton(classType):

classType._instance = None

classType._lock = Lock()

classType.getInstance = classmethod(__getInstance)

return classType

1

2

3

4

5

6

7

8

9

10

11

12

13

def__getInstance(classType):

ifclassType._instanceisNone:

classType._lock.acquire()

ifclassType._instanceisNone:

classType._instance=classType()

classType._lock.release()

returnclassType._instance

defsingleton(classType):

classType._instance=None

classType._lock=Lock()

classType.getInstance=classmethod(__getInstance)

returnclassType

使用方法如下:

Python

@singleton

class XXX(object):

# add class definitions

pass

1

2

3

4

@singleton

classXXX(object):

# add class definitions

pass

二.可继承的单例模式

现在让我们为这个单例模式添加一些功能:我们让被这个单例类可以产生子类,且子类也是单例类,和父类共享同一个instance。为此,我们必须修改被修饰的单例类的init方法,在其中设置instance为自身:

Python

def __singleton_init(self):

# check whether instance has existed

if self._instance is not None:

raise SingletonExistedError(type(self))

# set instance of this class and its ancestor classes to self

for baseClass in inspect.getmro(type(self)):

if '_instance' in baseClass.__dict__:

baseClass._instance = self

1

2

3

4

5

6

7

8

9

def__singleton_init(self):

# check whether instance has existed

ifself._instanceisnotNone:

raiseSingletonExistedError(type(self))

# set instance of this class and its ancestor classes to self

forbaseClassininspect.getmro(type(self)):

if'_instance'inbaseClass.__dict__:

baseClass._instance=self

SingletonExistedError为自定义的error类型:

Python

class SingletonExistedError(Exception):

def __init__(self, classType):

super(SingletonExistedError, self).__init__('trying to construct instance of singleton class ' + classType.__name__ + ' while an instance has already existed!')

1

2

3

classSingletonExistedError(Exception):

def__init__(self,classType):

super(SingletonExistedError,self).__init__('trying to construct instance of singleton class '+classType.__name__+' while an instance has already existed!')

现在我们需要把这个新的init函数添加到被修饰的单例类的init函数上。很自然的,我们又可以利用函数的decorator来办成这件事情,就像这样:

Python

def __singleton_init_decorator(init_func):

def __singleton_init(self):

# check whether instance has existed

if self._instance is not None:

raise SingletonExistedError(type(self))

# set instance of the class and ancestor singletons to self

for baseClass in inspect.getmro(type(self)):

if '_instance' in baseClass.__dict__:

baseClass._instance = self

init_func(self)

return __singleton_init

1

2

3

4

5

6

7

8

9

10

11

12

13

def__singleton_init_decorator(init_func):

def__singleton_init(self):

# check whether instance has existed

ifself._instanceisnotNone:

raiseSingletonExistedError(type(self))

# set instance of the class and ancestor singletons to self

forbaseClassininspect.getmro(type(self)):

if'_instance'inbaseClass.__dict__:

baseClass._instance=self

init_func(self)

return__singleton_init

最后,在我们的singleton decorator上加上这句代码:

Python

classType.__init__ = __singleton_init_decorator(classType.__init__)

1

classType.__init__=__singleton_init_decorator(classType.__init__)

大功告成!附上完整代码:

Python

class SingletonExistedError(Exception):

def __init__(self, classType):

super(SingletonExistedError, self).__init__('trying to construct instance of singleton class ' + classType.__name__ + ' while an instance has already existed!')

def __getInstance(classType):

if classType._instance is None:

classType._lock.acquire()

if classType._instance is None:

classType._instance = classType()

classType._lock.release()

return classType._instance

def __singleton_init_decorator(init_func):

def __singleton_init(self):

# check whether instance has existed

if self._instance is not None:

raise SingletonExistedError(type(self))

# set instance of the class and ancestor singletons to self

for baseClass in inspect.getmro(type(self)):

if '_instance' in baseClass.__dict__:

baseClass._instance = self

init_func(self)

return __singleton_init

def singleton(classType):

classType._instance = None

classType._lock = Lock()

classType.getInstance = classmethod(__getInstance)

classType.__init__ = __singleton_init_decorator(classType.__init__)

return classType

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

classSingletonExistedError(Exception):

def__init__(self,classType):

super(SingletonExistedError,self).__init__('trying to construct instance of singleton class '+classType.__name__+' while an instance has already existed!')

def__getInstance(classType):

ifclassType._instanceisNone:

classType._lock.acquire()

ifclassType._instanceisNone:

classType._instance=classType()

classType._lock.release()

returnclassType._instance

def__singleton_init_decorator(init_func):

def__singleton_init(self):

# check whether instance has existed

ifself._instanceisnotNone:

raiseSingletonExistedError(type(self))

# set instance of the class and ancestor singletons to self

forbaseClassininspect.getmro(type(self)):

if'_instance'inbaseClass.__dict__:

baseClass._instance=self

init_func(self)

return__singleton_init

defsingleton(classType):

classType._instance=None

classType._lock=Lock()

classType.getInstance=classmethod(__getInstance)

classType.__init__=__singleton_init_decorator(classType.__init__)

returnclassType

python单例模式继承_python单例模式相关推荐

  1. python多继承_python作用域和多继承

    python作用域 python无块级作用域 看c语言代码: #include intmain() {if(2 > 0) {int i = 0; } printf("i = %d&qu ...

  2. python单例模式继承_Python四种实现单例模式的方法

    在这之前,先了解super()和__new__()方法 super()方法: 返回一个父类或兄弟类类型的代理对象,让你能够调用一些从继承过来的方法. 它有两个典型作用: a. 在单继承的类层次结构中, ...

  3. python单例_Python - 单例模式(Singleton)

    单例模式(Singleton) 本文地址: http://blog.csdn.net/caroline_wendy/article/details/23374575 单例模式 , 类的实例从始至终, ...

  4. python单例_Python单例模式

    所谓单例,是指一个类的实例从始至终只能被创建一次,,而且自行实例化并向整个系统提供这个实例. 方法1 如果想使得某个类从始至终最多只有一个实例,使用__new__方法会很简单.Python中类是通过_ ...

  5. python单例_python 单例模式

    单例模式 单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在.当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场. ...

  6. python怎么继承_Python: 如何继承str/string?

    想搞一个对象继承自str,然后存一些额外信息用来标识这个字符串,然后理所当然地重写了__init__发现跪了: class newstring(str): def __init__(self, val ...

  7. python编程语言继承_python应用:学习笔记(Python继承)

    学习笔记(Python继承)Python是一种解释型脚本语言,可以应用于以下领域: web 和 Internet开发 科学计算和统计 人工智能 教育 桌面界面开发 后端开发 网络爬虫 有几种叫法(父类 ...

  8. python类变量继承_python 类的成员及继承

    1. @staticmethod 静态方法 静态方法不能访问实例变量和类变量,除了身处类里面,所以只能通过类调用以外,它其实和类没有什么关系.如果想要用它访问实例变量或类变量,需要把实例和类传递给函数 ...

  9. python面向对象继承_Python 面向对象 --- 继承

    目标 单继承 多继承 面向对象三大特性 1,封装 根据 职责 将 属性 和 方法 封装 到以抽象的 类 中 2,继承 实现代码的重用,相同的代码不需要重复的缩写 3,多态 不同的对象调用相同的方法,产 ...

  10. python 构造函数继承_Python多重继承的异构构造器

    在Python里面,如果你使用上Qt,SQLAlchemy,Twisted之类各种大型类库时候,有时候多重继承Multiple Inheritance是个简单的解决方法,但是多重继承的复杂性总容易造成 ...

最新文章

  1. 文件系统的两种文件索引模式extent和blockmap
  2. 好文转发《我现在是这样编程的》
  3. 将ubuntu的apache2修改成https链接
  4. 微软下周将发布重磅安全公告 修复40个漏洞
  5. Kubernetes详解(三)——Kubernetes集群组件
  6. junit 生成html报告,gradle – 如何为JUnit 5测试创建HTML报告?
  7. 计算机的清楚键盘是,电脑键盘上按哪个键是删除键?
  8. tp6 中的save()使用说明
  9. 女生做数据分析师累吗?零基础可以转行吗?
  10. wkhtmltopdf(thead)分页问题
  11. 怎么写竞品分析报告(思路):
  12. c语言 ptr 用法,C++之智能指针std::shared_ptr简单使用和理解
  13. Applied Flow Technology Fathom v7.0 2011.03.22 1CD
  14. Bat大厂程序员常用的IDE工具,你接触过哪些?
  15. 实收资本和注册资本\营业执照和法人营业执照的区别
  16. 入门学习:网络营销的新手们,赶紧来了解一下吧!
  17. 树莓派安装开源项目——wukong_robot和魔镜结合 个人经验总结
  18. UCI mutilpexing PUSCH
  19. 开发编程-创意个人简历
  20. 成都市武侯区计算机实验小学校长,成都武侯计算机实验小学在“博雅”文化沁润下绽放美丽花朵...

热门文章

  1. psvimg格式PSV存档文件解包工具psvimgtools在macOS环境下的使用教程
  2. require.js加载highcharts.js/exporting.js实现图表的绘制和图片文件功能的导出
  3. App Store与苹果签名
  4. 神奇的大脑 神经网络
  5. 第五讲 交错级数、绝对收敛和条件收敛
  6. Spring boot 集成极光推送
  7. 基于libGPE读写KML文件的研究
  8. 阿里巴巴矢量字体转Image图片(建议收藏)
  9. 详细叙述网上现有的PS换脸术(附步骤总结)
  10. 无法下载文件或程序时的解决方法