Python單例模式的實現方式

一.單例類

單例模式(Singleton Pattern)是 Python 中最簡單的設計模式之一。這種類型的設計模式屬於建立型模式,它提供了一種建立對象的最佳方式。html

這種模式涉及到一個單一的類,該類負責建立本身的對象,同時確保只有單個對象被建立。這個類提供了一種訪問其惟一的對象的方式,能夠直接訪問,不須要實例化該類的對象。python

注意點:設計模式

  • 一、單例類只能有一個實例。
  • 二、單例類必須本身建立本身的惟一實例。
  • 三、單例類必須給全部其餘對象提供這一實例。

二.單例模式實現方式

# 1.使用__new__方法實現:
class MyTest(object): _instance = None def __new__(cls, *args, **kw): if not cls._instance: cls._instance = super().__new__(cls, *args, **kw) return cls._instance
class Mytest(MyTest): a = 1

# 結果以下
>>> a = MyTest()
>>> b = MyTest()
>>> a == b
True
>>> a is b
True
>>> id(a), id(b)
(2339876794776,2339876794776)
 
 
# 2.裝飾器方式實現
def outer(cls, *args, **kw):
instance = {}

def inner():
if cls not in instance:
instance[cls] = cls(*args, **kw)
return instance[cls]

return inner


@outer
class Mytest(object):
def __init__(self):
self.num_sum = 0

def add(self):
self.num_sum = 100
# 結果以下
>>> a = MyTest()
>>> b = MyTest()
>>> id(a), id(b)
(1878000497048,1878000497048)

 

# 3.使用元類實現
class Mytest(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]

# Python2
class MyTest(object):
__metaclass__ = Mytest


# Python3
class MyTest(metaclass=Mytest):
  pass
>>> a = MyTest()
>>> b = MyTest()
>>> id(a), id(b)
(1878000497048,1878000497048)

原文出處:https://www.cnblogs.com/yushenglin/p/10918983.htmlspa

相關文章
相關標籤/搜索