裝飾器實現單例模式

what is singleton pattern?

the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions a

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 Test(object):
    pass
one = Test()
two = Test()
print "one id=%s" % id(one)
print "two id=%s" % id(two)

one id=140313354635728

two id=140313354635728

one 和 two的id一樣,所以他們是同一個實例

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章