• 新式类单例模式之 __new__()


    单例模式:

    确保一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

    类中有一个静态属性__instance,默认为none,重构__new__()方法,判断__instance是否为空,若为空则
    Singleton.__instance = object.__new__(cls,*args,**kwargs),若不为空则证明该类已经被创建了实例,则此时将返回__instance,实现单例模式。

    class Singleton(object):
        __instance = None
        def __init__(self):
            pass
    
        def __new__(cls, *args, **kwargs):
            if not Singleton.__instance:
                Singleton.__instance = object.__new__(cls,*args, **kwargs)
            return Singleton.__instance
    
    
    class Commoncls(object):
        pass
    
    obj1,obj2 = Singleton(),Singleton()
    
    obj3,obj4 = Commoncls(),Commoncls()
    
    if obj1 == obj2:
        print('两个是一样的')
    else:
        print('两个不是一样的')
    
    if obj3 == obj4:
        print('两个是一样的')
    else:
        print('两个不是一样的')
  • 相关阅读:
    Dubbo监控中心
    Dubbo 提供者配置&测试
    IDEA中pom.xml依赖另一个项目
    MBG
    查询优化技术之多级缓存
    分布式扩展流程
    Redis取值时取出的是HashMap
    linux执行sql
    Git的使用
    405
  • 原文地址:https://www.cnblogs.com/n1celll/p/10750659.html
Copyright © 2020-2023  润新知