简介:该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场

1. 最简单方式(使用模块)

Python的模块是天然单例模式

建立<font style="color:#F5222D;">explame.py</font>文件

  1. class mySingleton:
  2. def test(self):
  3. pass
  4. mySle = mySingleton()

保存之后,要使用时,导入其他文件内,对象即是单例模式的对象

  1. from testFile import mySle

2.装饰器方式

  1. def mySingle(cls):
  2. _instance = {}
  3. def _mysingle(*args, **kargs):
  4. if cls not in _instance:
  5. _instance[cls] = cls(*args, **kargs)
  6. return _instance[cls]
  7. return _mysingle
  8. @mySingle
  9. class Test1(object):
  10. a = 1
  11. def __init__(self, x=0):
  12. self.x = x
  13. a1 = Test1(2)
  14. a2 = Test1(3)

3.基于new方法实现(方便)

我们知道,当我们实例化一个对象时,是先执行了类的new方法(我们没写时,默认调用object.new),实例化对象;然后再执行类的init方法,对这个对象进行初始化,所有我们可以基于这个,实现单例模式
  1. import threading
  2. class mySingle(object):
  3. _instance_lock = threading.Lock()
  4. def __init__(self):
  5. pass
  6. def __new__(cls, *args, **kwargs):
  7. if not hasattr(mySingle, "_instance"):
  8. with mySingle._instance_lock:
  9. if not hasattr(mySingle, "_instance"):
  10. mySingle._instance = object.__new__(cls)
  11. return mySingle._instance
  12. obj1 = mySingle()
  13. obj2 = mySingle()
  14. print(obj1,obj2)
  15. def task(arg):
  16. obj = mySingle()
  17. print(f'{obj}---{arg}')
  18. for i in range(10):
  19. t = threading.Thread(target=task,args=[i,])
  20. t.start()
  21. ==========================================================================
  22. 打印结果:
  23. <__main__.mySingle object at 0x0000000002619700> <__main__.mySingle object at 0x0000000002619700>
  24. <__main__.mySingle object at 0x0000000002619700>---0
  25. <__main__.mySingle object at 0x0000000002619700>---1
  26. <__main__.mySingle object at 0x0000000002619700>---2
  27. <__main__.mySingle object at 0x0000000002619700>---3
  28. <__main__.mySingle object at 0x0000000002619700>---4
  29. <__main__.mySingle object at 0x0000000002619700>---5
  30. <__main__.mySingle object at 0x0000000002619700>---6
  31. <__main__.mySingle object at 0x0000000002619700>---7
  32. <__main__.mySingle object at 0x0000000002619700>---8
  33. <__main__.mySingle object at 0x0000000002619700>---9