国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python設(shè)計模式之單例模式實例

2020-02-23 05:21:13
字體:
供稿:網(wǎng)友

注:使用的是Python 2.7。

一個簡單實現(xiàn)
代碼如下:
class Foo(object):
    __instance = None
    def __init__(self):
        pass
    @classmethod
    def getinstance(cls):
        if(cls.__instance == None):
            cls.__instance = Foo()
        return cls.__instance

if __name__ == '__main__':
    foo1 = Foo.getinstance()
    foo2 = Foo.getinstance()
    print id(foo1)
    print id(foo2)
    print id(Foo())
輸出的前兩個結(jié)果是相同的(id(foo1)與id(foo2)的值相同),第三個結(jié)果和前兩個不同。這里類方法getinstance()用于獲取單例,但是類本身也可以實例化,這樣的方式其實并不符合單例模式的要求。但是這樣做也有好處,代碼簡單,大家約定好這樣子調(diào)用就行了。但是最好在類的命名上也體現(xiàn)了出來這是一個單例類,例如Foo_singleton。

換一個思路

先說一下init和new的區(qū)別:
代碼如下:
class Foo(object):
    __instance = None
    def __init__(self):
        print 'init'
if __name__ == '__main__':
    foo = Foo()
運行結(jié)果是:
代碼如下:
init
而下面的示例:
代碼如下:
class Foo(object):
    __instance = None
    def __init__(self):
        print 'init'
    def __new__(cls, *args, **kwargs):
        print 'new'

if __name__ == '__main__':
    foo = Foo()
運行結(jié)果是:
代碼如下:new

new是一個類方法,會創(chuàng)建對象時調(diào)用。而init方法是在創(chuàng)建完對象后調(diào)用,對當(dāng)前對象的實例做一些一些初始化,無返回值。如果重寫了new而在new里面沒有調(diào)用init或者沒有返回實例,那么init將不起作用。以下內(nèi)容引用自http://docs.python.org/2/reference/datamodel.html#object.new
代碼如下:
If __new__() returns an instance of cls, then the new instance's __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().

If __new__() does not return an instance of cls, then the new instance's __init__() method will not be invoked.
這樣做:
代碼如下:
class Foo(object):
    __instance = None
    def __init__(self):
        print 'init'

    def __new__(cls, *args, **kwargs):
        print 'new'
        if cls.__instance == None:

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 昌江| 城口县| 伊宁市| 宜川县| 安义县| 安阳县| 吴堡县| 阿勒泰市| 广西| 无锡市| 库尔勒市| 广平县| 满城县| 广昌县| 白山市| 化隆| 富宁县| 通化县| 西林县| 突泉县| 旺苍县| 五家渠市| 永顺县| 奉贤区| 文山县| 亚东县| 确山县| 灵山县| 南汇区| 兴安盟| 二手房| 霍城县| 衡东县| 临漳县| 宜城市| 剑河县| 保亭| 仁怀市| 庄浪县| 辽阳县| 鸡东县|