Python中的單例模式——裝飾器實現剖析

來源:互聯網
上載者:User

標籤:思想   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中的單例模式——裝飾器實現剖析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.