python面向对象之单例模式

单例模式

第一阶段:普通模式

NAME = 'PLF'
AGE = 18
class Foo:
    __instance = None

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

    @classmethod
    def func(cls):
        if cls.__instance:
            return cls.__instance

        obj = cls(NAME,AGE)
        cls.__instance = obj
        return  obj

one = Foo.func()
two = Foo.func()
three = Foo.func()
four = Foo.func()
print(id(one))
print(id(two))
print(id(three))
print(id(four))
1734533208384
1734533208384
1734533208384
1734533208384

总结:通过类属性保存创建的第一个对象,之后对类属性进行判断,类属性有值则一直沿用类属性的值(对象),没有则创建。

第二阶段:进阶

NAME = 'PLF'
AGE = 18
def deco(cls):
    cls.__instance = cls(NAME,AGE)
    def wrapper(*args,**kwargs):
        if len(args) == 0 and len(kwargs) == 0:
            return cls.__instance
        res = cls(*args,**kwargs)
        return res
    return wrapper

@deco
class Foo:
    __instance = None
    def __init__(self,name,age):
        self.name = name
        self.age = age

ori = Foo() # Foo() = wrapper() ,没有加参数使用默认初始化
print(ori.name,ori.age)     

one = Foo('LT',100)     # 用户添加参数,则使用用户的参数进行初始化,不使用
print(one.name,one.age)
PLF 18
LT 100

第三阶段:最正宗的模式

NAME = 'PLF'
AGE = 18
class Foo(type):
    def __init__(self,class_name,class_bases,class_dict):
        super().__init__(class_name,class_bases,class_dict)
        self.instance = self(NAME,AGE)

    def __call__(self, *args, **kwargs):
        if self.instance:
            return self.instance
        obj = object.__new__(self)
        self.__init__(obj,*args,**kwargs)
        return obj


class Person(metaclass=Foo):
    instance = None
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def run(self):
        print("run")

    def eat(self):
        print("eat")

one = Person('zhangsan',20)
two = Person()
three = Person()
print(one)
print(two)
print(three)
<__main__.Person object at 0x000002A4FC2741D0>
<__main__.Person object at 0x000002A4FC2741D0>
<__main__.Person object at 0x000002A4FC2741D0>

通过类属性将我们自己的实例对象保留下来,之后再创建就一直使用类属性中的实例对象

转载于:https://www.cnblogs.com/plf-Jack/p/11066402.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值