单例模式---python实现

单例模式就是一个类只能有一个对象,这个对象是这个类的全局访问点,下面是对单例模式的python实现
经典单例模式

class Singleton(object):
    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super(Singleton, cls).__new__(cls)
            return cls.instance


s = Singleton()

print("Object created", s)
s2 = Singleton()
print("Object created", s2)

懒汉式单例模式

#  保证使用时才真正需要创建对象

class Singleton:
    __instance = None
    def __init__(self):
        if not Singleton.__instance:
            print("__init__method called..")
        else:
            print("Instance already created:", self.getInstance())

    @classmethod
    def getInstance(cls):
        if not cls.__instance:
            cls.__instance = Singleton()
        return cls.__instance


s = Singleton()
print("Object created", Singleton.getInstance())

s1 = Singleton()

Monostate单例模式

class Borg:
    __share__state = {"1":"2"}
    def __init__(self):
        self.x = 1
        self.__dict__ = self.__share__state
        pass

b = Borg()
b1 = Borg()
b.x = 4

print("Borg Object 'b':",b)
print("Borg Object 'b1':",b1)
print("Borg Object 'b':",b.__dict__)
print("Borg Object 'b1':",b1.__dict__)

你可能感兴趣的:(设计模式,python,单例模式,开发语言)