github地址:https://github.com/cheesezh/python_design_patterns

单例模式

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

比如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信息。如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例,这就导致系统中存在多个 AppConfig 的实例对象,而这样会严重浪费内存资源,尤其是在配置文件内容很多的情况下。事实上,类似 AppConfig 这样的类,我们希望在程序运行期间只存在一个实例对象。

在 Python 中,我们可以用多种方法来实现单例模式。

使用模块

其实,Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。如果我们真的想要一个单例类,可以考虑这样做:

  1. # mysingleton.py
  2. class Singleton(object):
  3. def foo(self):
  4. pass
  5. singleton = Singleton()

将上面的代码保存在文件 mysingleton.py 中,要使用时,直接在其他文件中导入此文件中的对象,这个对象即是单例模式的对象

  1. from a import singleton

使用装饰器

  1. def Singleton(cls):
  2. _instance = {}
  3. def _singleton(*args, **kargs):
  4. if cls not in _instance:
  5. _instance[cls] = cls(*args, **kargs)
  6. return _instance[cls]
  7. return _singleton
  8. @Singleton
  9. class A(object):
  10. a = 1
  11. def __init__(self, x=0):
  12. self.x = x
  13. a1 = A(2)
  14. a2 = A(3)
  15. print(a1)
  16. print(a2)
  1. <__main__.A object at 0x103496668>
  2. <__main__.A object at 0x103496668>

使用类

  1. class Singleton(object):
  2. def __init__(self):
  3. pass
  4. @classmethod
  5. def instance(cls, *args, **kwargs):
  6. if not hasattr(Singleton, "_instance"):
  7. Singleton._instance = Singleton(*args, **kwargs)
  8. return Singleton._instance

一般情况,大家以为这样就完成了单例模式,但是这样当使用多线程时会存在问题

  1. class Singleton(object):
  2. def __init__(self):
  3. pass
  4. @classmethod
  5. def instance(cls, *args, **kwargs):
  6. if not hasattr(Singleton, "_instance"):
  7. Singleton._instance = Singleton(*args, **kwargs)
  8. return Singleton._instance
  9. import threading
  10. def task(arg):
  11. obj = Singleton.instance()
  12. print(obj)
  13. for i in range(10):
  14. t = threading.Thread(target=task,args=[i,])
  15. t.start()
  1. <__main__.Singleton object at 0x1033e84a8>
  2. <__main__.Singleton object at 0x1033e84a8>
  3. <__main__.Singleton object at 0x1033e84a8>
  4. <__main__.Singleton object at 0x1033e84a8>
  5. <__main__.Singleton object at 0x1033e84a8>
  6. <__main__.Singleton object at 0x1033e84a8>
  7. <__main__.Singleton object at 0x1033e84a8>
  8. <__main__.Singleton object at 0x1033e84a8>
  9. <__main__.Singleton object at 0x1033e84a8>
  10. <__main__.Singleton object at 0x1033e84a8>

看起来也没有问题,那是因为执行速度过快,如果在init方法中有一些IO操作,就会发现问题了,下面我们通过time.sleep模拟

  1. class Singleton(object):
  2. def __init__(self):
  3. import time
  4. time.sleep(0.5)
  5. pass
  6. @classmethod
  7. def instance(cls, *args, **kwargs):
  8. if not hasattr(Singleton, "_instance"):
  9. Singleton._instance = Singleton(*args, **kwargs)
  10. return Singleton._instance
  11. import threading
  12. def task(arg):
  13. obj = Singleton.instance()
  14. print(obj)
  15. for i in range(10):
  16. t = threading.Thread(target=task,args=[i,])
  17. t.start()
  1. <__main__.Singleton object at 0x1033b79e8>
  2. <__main__.Singleton object at 0x1033b7e10>
  3. <__main__.Singleton object at 0x103401ef0>
  4. <__main__.Singleton object at 0x103401c18>
  5. <__main__.Singleton object at 0x103401048>
  6. <__main__.Singleton object at 0x103401dd8>
  7. <__main__.Singleton object at 0x103401b00>
  8. <__main__.Singleton object at 0x103401eb8>
  9. <__main__.Singleton object at 0x103401a58>
  10. <__main__.Singleton object at 0x103401fd0>

问题出现了!按照以上方式创建的单例,无法支持多线程。

解决办法:加锁!未加锁部分并发执行,加锁部分串行执行,速度降低,但是保证了数据安全

  1. import time
  2. import threading
  3. class Singleton(object):
  4. _instance_lock = threading.Lock()
  5. def __init__(self):
  6. time.sleep(0.5)
  7. @classmethod
  8. def instance(cls, *args, **kwargs):
  9. with Singleton._instance_lock:
  10. if not hasattr(Singleton, "_instance"):
  11. Singleton._instance = Singleton(*args, **kwargs)
  12. return Singleton._instance
  13. def task(arg):
  14. obj = Singleton.instance()
  15. print(obj)
  16. for i in range(10):
  17. t = threading.Thread(target=task,args=[i,])
  18. t.start()
  19. time.sleep(5)
  20. obj = Singleton.instance()
  21. print(obj)
  1. <__main__.Singleton object at 0x103401b00>
  2. <__main__.Singleton object at 0x103401b00>
  3. <__main__.Singleton object at 0x103401b00>
  4. <__main__.Singleton object at 0x103401b00>
  5. <__main__.Singleton object at 0x103401b00>
  6. <__main__.Singleton object at 0x103401b00>
  7. <__main__.Singleton object at 0x103401b00>
  8. <__main__.Singleton object at 0x103401b00>
  9. <__main__.Singleton object at 0x103401b00>
  10. <__main__.Singleton object at 0x103401b00>
  11. <__main__.Singleton object at 0x103401b00>

这样就差不多了,但是还是有一点小问题,就是当程序执行时,执行了time.sleep(5)后,下面实例化对象时,此时已经是单例模式了,但我们还是加了锁,这样不太好,再进行一些优化,需要修改一下intance方法。

  1. import time
  2. import threading
  3. class Singleton(object):
  4. _instance_lock = threading.Lock()
  5. def __init__(self):
  6. time.sleep(0.5)
  7. @classmethod
  8. def instance(cls, *args, **kwargs):
  9. if not hasattr(Singleton, "_instance"):
  10. with Singleton._instance_lock:
  11. if not hasattr(Singleton, "_instance"):
  12. Singleton._instance = Singleton(*args, **kwargs)
  13. return Singleton._instance
  14. def task(arg):
  15. obj = Singleton.instance()
  16. print(obj)
  17. for i in range(10):
  18. t = threading.Thread(target=task,args=[i,])
  19. t.start()
  20. time.sleep(5)
  21. obj = Singleton.instance()
  22. print(obj)
  1. <__main__.Singleton object at 0x1033db550>
  2. <__main__.Singleton object at 0x1033db550>
  3. <__main__.Singleton object at 0x1033db550>
  4. <__main__.Singleton object at 0x1033db550>
  5. <__main__.Singleton object at 0x1033db550>
  6. <__main__.Singleton object at 0x1033db550>
  7. <__main__.Singleton object at 0x1033db550>
  8. <__main__.Singleton object at 0x1033db550>
  9. <__main__.Singleton object at 0x1033db550>
  10. <__main__.Singleton object at 0x1033db550>
  11. <__main__.Singleton object at 0x1033db550>

这种方式实现的单例模式,使用时会有限制,以后实例化必须通过obj = Singleton.instance(),如果用obj=Singleton(),这种方式得到的不是单例。

使用__new__方法(推荐使用,方便)

通过上面例子,我们可以知道,当我们实现单例时,为了保证线程安全需要在内部加入锁。

我们知道,当我们实例化一个对象时,是先执行了类的__new__方法(我们没写时,默认调用object.new)实例化对象;然后再执行类的__init__方法,对这个对象进行初始化,所有我们可以基于这个机制,实现单例模式。

  1. import threading
  2. import time
  3. class Singleton(object):
  4. _instance_lock = threading.Lock()
  5. def __init__(self):
  6. time.sleep(0.5)
  7. def __new__(cls, *args, **kwargs):
  8. if not hasattr(Singleton, "_instance"):
  9. with Singleton._instance_lock:
  10. if not hasattr(Singleton, "_instance"):
  11. Singleton._instance = object.__new__(cls)
  12. return Singleton._instance
  13. obj1 = Singleton()
  14. obj2 = Singleton()
  15. print(obj1,obj2)
  16. def task(arg):
  17. obj = Singleton()
  18. print(obj)
  19. for i in range(10):
  20. t = threading.Thread(target=task,args=[i,])
  21. t.start()
  1. <__main__.Singleton object at 0x103483b70> <__main__.Singleton object at 0x103483b70>
  2. <__main__.Singleton object at 0x103483b70>
  3. <__main__.Singleton object at 0x103483b70>
  4. <__main__.Singleton object at 0x103483b70>
  5. <__main__.Singleton object at 0x103483b70>
  6. <__main__.Singleton object at 0x103483b70>
  7. <__main__.Singleton object at 0x103483b70>
  8. <__main__.Singleton object at 0x103483b70>
  9. <__main__.Singleton object at 0x103483b70>
  10. <__main__.Singleton object at 0x103483b70>
  11. <__main__.Singleton object at 0x103483b70>

采用这种方式的单例模式,以后实例化对象时,和平时实例化对象的方法一样obj = Singleton()

使用metaclass

  1. 类由type创建,创建类时,type的__init__方法自动执行,类()执行type的__call__方法(类的__new__方法,类的__init__方法)
  2. 对象由类创建,创建对象时,类的__init__方法自动执行,对象()执行类的__call__方法
  1. class Foo:
  2. def __init__(self):
  3. print("Foo __init__")
  4. def __call__(self, *args, **kwargs):
  5. print("Foo __call__")
  6. # 执行type的 __call__ 方法
  7. # 调用 Foo类(是type的对象)的 __new__方法,用于创建对象
  8. # 然后调用 Foo类(是type的对象)的 __init__方法,用于对对象初始化。
  9. obj = Foo()
  10. # 执行Foo的 __call__ 方法
  11. obj()
  1. Foo __init__
  2. Foo __call__
  1. class SingletonType(type):
  2. def __init__(self,*args,**kwargs):
  3. super(SingletonType,self).__init__(*args,**kwargs)
  4. def __call__(cls, *args, **kwargs): # 这里的cls,即Foo类
  5. print('cls',cls)
  6. obj = cls.__new__(cls,*args, **kwargs)
  7. cls.__init__(obj,*args, **kwargs) # Foo.__init__(obj)
  8. return obj
  9. class Foo(metaclass=SingletonType): # 指定创建Foo的type为SingletonType
  10. def __init__(self, name):
  11. self.name = name
  12. def __new__(cls, *args, **kwargs):
  13. return object.__new__(cls)
  14. obj = Foo('xx')
  1. cls <class '__main__.Foo'>
  1. import threading
  2. class SingletonType(type):
  3. _instance_lock = threading.Lock()
  4. def __call__(cls, *args, **kwargs):
  5. if not hasattr(cls, "_instance"):
  6. with SingletonType._instance_lock:
  7. if not hasattr(cls, "_instance"):
  8. cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
  9. return cls._instance
  10. class Foo(metaclass=SingletonType):
  11. def __init__(self,name):
  12. self.name = name
  13. obj1 = Foo('name')
  14. obj2 = Foo('name')
  15. print(obj1)
  16. print(obj2)
  1. <__main__.Foo object at 0x10348d908>
  2. <__main__.Foo object at 0x10348d908>

参考文章: Python中的单例模式的几种实现方式的及优化

[Python设计模式] 第21章 计划生育——单例模式的更多相关文章

  1. [Python设计模式] 第1章 计算器——简单工厂模式

    github地址:https://github.com/cheesezh/python_design_patterns 写在前面的话 """ 读书的时候上过<设计模 ...

  2. python设计模式第五天【单例模式】

    1. 定义 一个类只有一个实例,提供访问该实例的全局方法 2.应用场景 (1)多线程之间共享对象资源 (2)整个程序空间中的全局变量,共享资源 (3)大规模程序的节省创建对象的时间 3.代码实现(使用 ...

  3. [Python设计模式] 第26章 千人千面,内在共享——享元模式

    github地址:https://github.com/cheesezh/python_design_patterns 背景 有6个客户想做产品展示网站,其中3个想做成天猫商城那样的"电商风 ...

  4. [Python设计模式] 第22章 手机型号&软件版本——桥接模式

    github地址:https://github.com/cheesezh/python_design_patterns 紧耦合程序演化 题目1 编程模拟以下情景,有一个N品牌手机,在上边玩一个小游戏. ...

  5. [Python设计模式] 第16章 上班,干活,下班,加班——状态模式

    github地址:https://github.com/cheesezh/python_design_patterns 题目 用代码模拟一天的工作状态,上午状态好,中午想睡觉,下午渐恢复,加班苦煎熬. ...

  6. [Python设计模式] 第9章 如何准备多份简历——原型模式

    github地址:https://github.com/cheesezh/python_design_patterns 题目 设计一个简历类,必须有姓名,可以设置性别和年龄,即个人信息,可以设置曾就职 ...

  7. [Python设计模式] 第7章 找人帮忙追美眉——代理模式

    github地址:https://github.com/cheesezh/python_design_patterns 题目1 Boy追求Girl,给Girl送鲜花,送巧克力,送洋娃娃. class ...

  8. [Python设计模式] 第28章 男人和女人——访问者模式

    github地址:https://github.com/cheesezh/python_design_patterns 题目 用程序模拟以下不同情况: 男人成功时,背后多半有一个伟大的女人: 女人成功 ...

  9. [Python设计模式] 第27章 正则表达式——解释器模式

    github地址:https://github.com/cheesezh/python_design_patterns 解释器模式 解释器模式,给定一个语言,定一个它的文法的一种表示,并定一个一个解释 ...

随机推荐

  1. 认识Fiddler

    一.Fiddler界面介绍.(注:下图中的功能区面板显示的是“Inspectors”的选项卡界面) 二.工具栏介绍. 1.气泡:备注.添加之后在会话栏的Comment列中显示备注内容. 2.Repla ...

  2. day30 网络编程 之进程,线程,协程

    进程点进去 线程点进去 协程点进去 什么是进程 进程(有时称为重量级进程)是一个执行中的程序.每个进程都拥有自己的地址空间.内存.数据栈以及其他用于跟踪执行的辅助数据.同一个程序执行两次,属于是两个不 ...

  3. python之psutil模块(获取系统性能信息(CPU,内存,磁盘,网络)

    一.psutil模块 1. psutil是一个跨平台库(http://code.google.com/p/psutil/),能够轻松实现获取系统运行的进程和系统利用率(包括CPU.内存.磁盘.网络等) ...

  4. Tomcat v9.0 Could not publish to the server. java.lang.IndexOutOfBoundsException

    今天使用Tomcat启动一个java项目,出现报错: Could not publish to the server. java.lang.IndexOutOfBoundsException 众寻之下 ...

  5. spring boot默认访问静态资源

    演示spring boot默认可以直接访问静态资源的2种方法: 第一种:在src/main/resources资源目录下创建一个名为"static"的文件夹(该文件夹的名称是规定死 ...

  6. 【C#】Convert.ToInt32、(int)和int.Parse三者的区别

    前者适合将object类类型转换成int类型 (int)适合简单数据类型之间的转换: int.Parse适合将string类类型转换成int类型.

  7. scrapy 安装

    windows 1.wheelpip install wheel2.lxmlhttp://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml3.PyOpensslhttp ...

  8. Xamarin Essentials教程使用指南针Compass

    Xamarin Essentials教程使用指南针Compass   指南针是一种确定地理方向的工具.在手机应用程序中,指南针通过手机的磁力计确定磁北极,提供手机方向信息.在Xamarin中,开发者可 ...

  9. 杭电1024----Max Sum Plus Plus

    /* 这题还没有理解透彻.某个dalao也不写注释.只能自己理解了... 先求为i个元素(1<=i<=M)为一个区间的最大和,保证元素个数大于等于i个,递推到M个即可 借鉴原址:http: ...

  10. 2、SQL UNION 和 UNION ALL 操作符

    网址:http://www.w3school.com.cn/sql/sql_union.asp SQL UNION 操作符 UNION 操作符用于合并两个或多个 SELECT 语句的结果集. 请注意, ...