Python中單例模式的裝飾器實現詳解解

2021-10-01 15:14:51 字數 1227 閱讀 8841

python中單例模式的實現方法有多種,但在這些方法中屬裝飾器版本用的廣,因為裝飾器是基於面向切面程式設計思想來實現的,具有很高的解耦性和靈活性。

單例模式定義:具有該模式的類只能生成乙個例項物件。

先將**寫上

'''

'''#建立實現單例模式的裝飾器

defsingleton

(cls,

*args,

**kwargs)

:  instances =

defget_instance

(*args,

**kwargs)

:if cls not

in instances:

instances[cls]

= cls(

*args,

**kwargs)

return instances[cls]

return 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裝飾器實現單例模式

基本思想為 1 在裝飾器中新增乙個字典型別的自由變數 instance 2 在閉包中判斷類名是否存在於 instance中,如果不存在則建立乙個類的事例,並講其新增到字典中 如果存在則不進行例項化,直接返回字典中的例項 def singleton cls instance def singleton...

Python裝飾器實現單例模式

coding utf 8 使用裝飾器 decorator 這是一種更pythonic,更elegant的方法,單例類本身根本不知道自己是單例的,因為他本身 自己的 並不是單例的 def singleton cls,args,kw instances def singleton if cls not ...

Python中利用裝飾器實現單例模式

python中裝飾器用在類上面,可以攔劫該類例項物件的建立,因此可以管理該類建立的所有例項,因此利用該特點可以實現單例模式。具體 如下 def singleton aclass instance none def oncall args nonlocal instance if instance n...