python-單例模式&原廠模式

來源:互聯網
上載者:User

標籤:UNC   war   ***   instance   singleton   style   屬性   ict   方法   

1.單例模式

  類外裝飾器實現單例模式,是攔截整個執行個體化過程。(__new__;__init__)

def singleton(cls):    _instance = {}    def func(*args,**kwargs):        if cls not in _instance:            _instance[cls] = cls(*args,**kwargs)        return _instance[cls]    return func@singletonclass Test(object):    def __init__(self,name):        self.name = nameif __name__ == ‘__main__‘:    a = Test(‘BOB‘)    b = Test(‘JON‘)    print(a is b)    print(id(a),id(b))
在上面,我們定義了一個裝飾器 singleton,它返回了一個內建函式 func,
該函數會判斷某個類是否在字典 _instances 中,如果不存在,則會將 cls 作為 key,cls(*args, **kwargs) 作為 value 存到 _instances 中,
否則,直接返回 _instances[cls]。
 

class Singleton(object):    _instance = None    def __new__(cls, *args, **kwargs):        if not cls._instance:            cls._instance = object.__new__(cls,*args,**kwargs)        return cls._instanceclass Test(Singleton):    def __init__(self):        self.name = ‘bob‘if __name__ == ‘__main__‘:    a = Test()    b = Test()        print(a is b)

*************************************************************************************************************************************************

# instance_dict = {}
#
# class B(object):
# __float = 0
#
# def __new__(cls, *args, **kwargs):
# if cls not in instance_dict:
# instance_dict[cls] = object.__new__(cls, *args, **kwargs)
#
# return instance_dict[cls]
#
# def __init__(self, name):
# if self.__float == 0:
# self.my_name = name
# self.__float = 1
#
#
# if __name__ == ‘__main__‘:
# a = B(1)
# b = B(2)
# print a.my_name, b.my_name
類內實現單例模式,只攔截了__new__產生對象的過程,沒有攔截初始化執行個體屬性的過程

攔截__new__方法實現單例模式,新式類為主









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.