python設計模式之--單例模式


python的單例模式就是一個類的實例只能自始自終自能創建一次。應用場景比如說數據庫的連接池。

#!/usr/bin/env python
# coding=utf-8

class Foo(object):

    instance = None

    def __init__(self, name):
        self.name = name


    @classmethod
    def get_instance(cls):
        if cls.instance:
            return cls.instance
        else:
            obj = cls('hexm')
            cls.instance = obj
            return obj

obj = Foo.get_instance()
obj1 = Foo.get_instance()
print(obj.name)
print(obj1.name)
print(Foo.instance)
print(obj)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM