歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python單例模式的4種實現方法

Python單例模式的4種實現方法

日期:2017/3/1 10:19:25   编辑:Linux編程

Python單例模式的4種實現方法:

  1. #-*- encoding=utf-8 -*-
  2. print '----------------------方法1--------------------------'
  3. #方法1,實現__new__方法
  4. #並在將一個類的實例綁定到類變量_instance上,
  5. #如果cls._instance為None說明該類還沒有實例化過,實例化該類,並返回
  6. #如果cls._instance不為None,直接返回cls._instance
  7. class Singleton(object):
  8. def __new__(cls, *args, **kw):
  9. if not hasattr(cls, '_instance'):
  10. orig = super(Singleton, cls)
  11. cls._instance = orig.__new__(cls, *args, **kw)
  12. return cls._instance
  13. class MyClass(Singleton):
  14. a = 1
  15. one = MyClass()
  16. two = MyClass()
  17. two.a = 3
  18. print one.a
  19. #3
  20. #one和two完全相同,可以用id(), ==, is檢測
  21. print id(one)
  22. #29097904
  23. print id(two)
  24. #29097904
  25. print one == two
  26. #True
  27. print one is two
  28. #True
  29. print '----------------------方法2--------------------------'
  30. #方法2,共享屬性;所謂單例就是所有引用(實例、對象)擁有相同的狀態(屬性)和行為(方法)
  31. #同一個類的所有實例天然擁有相同的行為(方法),
  32. #只需要保證同一個類的所有實例具有相同的狀態(屬性)即可
  33. #所有實例共享屬性的最簡單最直接的方法就是__dict__屬性指向(引用)同一個字典(dict)
  34. #可參看:http://code.activestate.com/recipes/66531/
  35. class Borg(object):
  36. _state = {}
  37. def __new__(cls, *args, **kw):
  38. ob = super(Borg, cls).__new__(cls, *args, **kw)
  39. ob.__dict__ = cls._state
  40. return ob
  41. class MyClass2(Borg):
  42. a = 1
  43. one = MyClass2()
  44. two = MyClass2()
  45. #one和two是兩個不同的對象,id, ==, is對比結果可看出
  46. two.a = 3
  47. print one.a
  48. #3
  49. print id(one)
  50. #28873680
  51. print id(two)
  52. #28873712
  53. print one == two
  54. #False
  55. print one is two
  56. #False
  57. #但是one和two具有相同的(同一個__dict__屬性),見:
  58. print id(one.__dict__)
  59. #30104000
  60. print id(two.__dict__)
  61. #30104000
  62. print '----------------------方法3--------------------------'
  63. #方法3:本質上是方法1的升級(或者說高級)版
  64. #使用__metaclass__(元類)的高級python用法
  65. class Singleton2(type):
  66. def __init__(cls, name, bases, dict):
  67. super(Singleton2, cls).__init__(name, bases, dict)
  68. cls._instance = None
  69. def __call__(cls, *args, **kw):
  70. if cls._instance is None:
  71. cls._instance = super(Singleton2, cls).__call__(*args, **kw)
  72. return cls._instance
  73. class MyClass3(object):
  74. __metaclass__ = Singleton2
  75. one = MyClass3()
  76. two = MyClass3()
  77. two.a = 3
  78. print one.a
  79. #3
  80. print id(one)
  81. #31495472
  82. print id(two)
  83. #31495472
  84. print one == two
  85. #True
  86. print one is two
  87. #True
  88. print '----------------------方法4--------------------------'
  89. #方法4:也是方法1的升級(高級)版本,
  90. #使用裝飾器(decorator),
  91. #這是一種更pythonic,更elegant的方法,
  92. #單例類本身根本不知道自己是單例的,因為他本身(自己的代碼)並不是單例的
  93. def singleton(cls, *args, **kw):
  94. instances = {}
  95. def _singleton():
  96. if cls not in instances:
  97. instances[cls] = cls(*args, **kw)
  98. return instances[cls]
  99. return _singleton
  100. @singleton
  101. class MyClass4(object):
  102. a = 1
  103. def __init__(self, x=0):
  104. self.x = x
  105. one = MyClass4()
  106. two = MyClass4()
  107. two.a = 3
  108. print one.a
  109. #3
  110. print id(one)
  111. #29660784
  112. print id(two)
  113. #29660784
  114. print one == two
  115. #True
  116. print one is two
  117. #True
  118. one.x = 1
  119. print one.x
  120. #1
  121. print two.x
  122. #1
Copyright © Linux教程網 All Rights Reserved