python單例模式
所謂單例,就是保證一個類僅有一個實例。所有引用(實例、對象)擁有相同的狀態(屬性)和行爲(方法);
同一個類的所有實例天然擁有相同的行爲(方法);
只需要保證同一個類的所有實例具有相同的狀態(屬性)即可;
所有實例共享屬性的最簡單最直接的方法就是__dict__屬性指向(引用)同一個字典(dict)
單例模式動機
對於系統中的某些類來說,只有一個實例很重要,例如,一個系統中可以存在多個打印任務,但是只能有一個正在打印的任務;一個系統中只能有一個串口管理器或文件系統;一個系統只能有一個計時工具或ID生成器。如在window是中就只能打開一個任務管理器。如果不使用機制對窗口對象進行唯一化,將彈出多個窗口,如果這些窗口顯示的內容完全一致,則是重複對象,浪費內存資源;如果這些窗口顯示的內容不一致,則意味着在某一瞬間系統有多個狀態,與實際不符,也會給用戶帶來誤解,不知道哪個纔是真實的狀態。因爲有時確保系統中某個對象的唯一性(即一個類只有一個實例)非常重要。
如何保證一個類只有一個實例並且這個實例易於被訪問呢?定義一個全局變量可以確保對象隨時都可以被訪問,但不能阻止我們實例化多個對象。一個更好的方法是讓類自身負責保存它的唯一實例。這個類可以保證沒有其他實例被創建,並且它可以提供一個訪問該實例的方法。這就是單例模式的模式動機。
單例模式要點
一是某個類只能有一個實例;
二是它必須自行創建這個實例;
三是它必須自行向整個系統提供這個實例。
從具體實現角度來說,就是一下三點:
一是單例模式的類只提供私有的構造函數;
二是類定義中含有一個該類的靜態私有對象;
三是該類提供了一個靜態的共有的函數用於創建或獲取它本身的靜態私有對象。
實現單例模式方法1:
- #/usr/bin/python
- #-*- encoding=utf-8 -*-
- #方法1,實現__new__方法
- #並在將一個類的實例綁定到類變量_instance上,
- #如果cls._instance爲None說明該類還沒有實例化過,實例化該類,並返回
- #如果cls._instance不爲None,直接返回cls._instance
- class Singleton(object):
- def __new__(cls, *args, **kw):
- if not hasattr(cls, '_instance'):
- orig = super(Singleton, cls)
- cls._instance = orig.__new__(cls, *args, **kw)
- return cls._instance
- class MyClass(Singleton):
- a = 1
- one = MyClass()
- two = MyClass()
- two.a = 3
- print one.a
- #3
- #one和two完全相同,可以用id(), ==, is檢測
- print id(one)
- #29097904
- print id(two)
- #29097904
- print one == two
- #True
- print one is two
- #True
實現單例模式方法2:
- #方法2,共享屬性;所謂單例就是所有引用(實例、對象)擁有相同的狀態(屬性)和行爲(方法)
- #同一個類的所有實例天然擁有相同的行爲(方法),
- #只需要保證同一個類的所有實例具有相同的狀態(屬性)即可
- #所有實例共享屬性的最簡單最直接的方法就是__dict__屬性指向(引用)同一個字典(dict)
- #可參看:http://code.activestate.com/recipes/66531/
- class Borg(object):
- _state = {}
- def __new__(cls, *args, **kw):
- ob = super(Borg, cls).__new__(cls, *args, **kw)
- ob.__dict__ = cls._state
- return ob
- class MyClass2(Borg):
- a = 1
- one = MyClass2()
- two = MyClass2()
- #one和two是兩個不同的對象,id, ==, is對比結果可看出
- two.a = 3
- print one.a
- #3
- print id(one)
- #28873680
- print id(two)
- #28873712
- print one == two
- #False
- print one is two
- #False
- #但是one和two具有相同的(同一個__dict__屬性),見:
- print id(one.__dict__)
- #30104000
- print id(two.__dict__)
- #30104000
實現單例模式方法3:
- #方法3:本質上是方法1的升級(或者說高級)版
- #使用__metaclass__(元類)的高級python用法
- class Singleton2(type):
- def __init__(cls, name, bases, dict):
- super(Singleton2, cls).__init__(name, bases, dict)
- cls._instance = None
- def __call__(cls, *args, **kw):
- if cls._instance is None:
- cls._instance = super(Singleton2, cls).__call__(*args, **kw)
- return cls._instance
- class MyClass3(object):
- __metaclass__ = Singleton2
- one = MyClass3()
- two = MyClass3()
- two.a = 3
- print one.a
- #3
- print id(one)
- #31495472
- print id(two)
- #31495472
- print one == two
- #True
- print one is two
- #True
實現單例模式方法4:
- #方法4:也是方法1的升級(高級)版本,
- #使用裝飾器(decorator),
- #這是一種更pythonic,更elegant的方法,
- #單例類本身根本不知道自己是單例的,因爲他本身(自己的代碼)並不是單例的
- def singleton(cls, *args, **kw):
- instances = {}
- def _singleton():
- if cls not in instances:
- instances[cls] = cls(*args, **kw)
- return instances[cls]
- return _singleton
- @singleton
- class MyClass4(object):
- a = 1
- def __init__(self, x=0):
- self.x = x
- one = MyClass4()
- two = MyClass4()
- two.a = 3
- print one.a
- #3
- print id(one)
- #29660784
- print id(two)
- #29660784
- print one == two
- #True
- print one is two
- #True
- one.x = 1
- print one.x
- #1
- print two.x
- #1