单例模式

2018-11-25  本文已影响0人  鲸随浪起

确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称为单例类,单例模式是一种对象创建型模式。

创建单例-保证只有1个对象

# 实例化一个单例
class Singleton(object):
    __instance = None

    def __new__(cls, age, name):
        #如果类数字能够__instance没有或者没有赋值
        #那么就创建一个对象,并且赋值为这个对象的引用,保证下次调用这个方法时
        #能够知道之前已经创建过对象了,这样就保证了只有1个对象
        if not cls.__instance:
            cls.__instance = object.__new__(cls)
        return cls.__instance

a = Singleton(18, "dongGe")
b = Singleton(8, "dongGe")

print(id(a))
print(id(b))

创建单例时,只执行1次init方法

class A(object):
    _instace = None
    def __new__(cls, *args, **kwargs):
        if not cls._instace:
            cls._instace = object.__new__(cls)
        return cls._instace
    def __init__(self,name):
        self.name = name
a = A("旺财")
print(id(a))
print(a.name)
b = A("哮天犬")
print(id(b))
print(b.name)

2019.5.23新添加

class Singleton:
    a1 = 1

    def __new__(cls,age,name):
        if not hasattr(cls,"_ins"):
            cls._ins = super().__new__(cls)
        return cls._ins
    def __init__(self,age,name):
        if not self.__first_init:
            self.age = age
            self.name = name
            self.__first_init = True
a = Singleton(18,"dongGe")
b = Singleton(8,"dongGe")

print(id(a))
print(id(b))

print(a.age)
print(b.age)
print(Singleton.a1)

上一篇 下一篇

猜你喜欢

热点阅读