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]。