標籤:思想 ret let 元類 執行個體 基於 **kwargs 函數名 war
Python中單例模式的實現方法有多種,但在這些方法中屬裝飾器版本用的廣,因為裝飾器是基於面向切面編程思想來實現的,具有很高的解耦性和靈活性。
單例模式定義:具有該模式的類只能產生一個執行個體對象。
先將代碼寫上
#建立實現單例模式的裝飾器
1 def singleton (cls, *args, **kwargs):
2 instances = {}
3 def get_instance (*args, **kwargs):
4 if cls not in instances:
5 instances[cls] = cls(*args, **kwargs)
6 return instances[cls]
7 return get_instance
程式碼分析:第1行,建立外層函數singleton,可以傳入類
第2行,建立一個instances字典用來儲存單例
第3行,建立一個內層函數來獲得單例
第4,5,6行, 判斷instances字典中是否含有單例,如果沒有就建立單例並儲存到instances字典中,然後返回該單例
第7行, 返回內層函數get_instance
#建立一個帶有裝飾器的類
@singleton
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
在Python中認為“一切皆對象”,類(元類除外)、函數都可以看作是對象,既然是對象就可以作為參數在函數中傳遞,我們現在來調用Student類來建立執行個體,看看實現過程。
#建立student執行個體
student = Student(jiang, 25)
@singleton相當於Student = singleton(Student),在建立執行個體對象時會先將 Student 作為參數傳入到 singleton 函數中,函數在執行過程中不會執行 get_instance 函數(函數只有調用才會執行),直接返回get_instance函數名。
此時可以看作Student = get_instance,建立執行個體時相當於student = get_instance(jiang, 25),調用get_instance 函數,先判斷執行個體是否在字典中,如果在直接從字典中擷取並返回,如果不在執行 instances [cls] = Student(jiang, 25),然後返回該執行個體對象並賦值非student變數,即student = instances[cls]。
Python中的單例模式——裝飾器實現剖析