• Python单例模式


    实现单例模式的三种方法:类实现、装饰器实现和元类实现

    #coding-utf-8
    
    #单例模式
    
    #类的方式实现单例模式
    '''class Singleton(object):
    
        _instance = None
        def __init__(self):
            print ("__init__")
            pass
    
        @staticmethod
        def __new__(cls, *argv, **kwargv):
           print ("__new__")
           if not cls._instance:
               cls._instance = super(Singleton, cls).__new__(cls,*argv, **kwargv)
    
           return cls._instance    
    
    class A(Singleton):pass'''
    
    #使用装饰器的方式实现单例模式
    '''def Singleton(cls):
        instances = {}
        
        def getinstance(*argv, **kwargv):
            if cls not in instances:
                instances[cls] = cls(*argv, **kwargv)   
            return instances[cls]
    
        return getinstance
    
    @Singleton
    class A(object):
        def __init__(self, parm):
            print ("class A __init__:%s" %(parm))'''
    
    #使用元类的方法实现单例模式
    class Singleton(type):
        instances = {}
        def __call__(self, *argv, **kwargv):
            if self not in self.instances:
                print ("!!!not have instances")
                self.instances[self] = super(Singleton, self).__call__(*argv, **kwargv)
            return super(Singleton, self).__call__(*argv, **kwargv)    
    
        def __new__(mcs, name, bases, namespace, **kwargs):
            print ("Singleton new")
            return super(Singleton, mcs).__new__(mcs,name, bases, namespace, **kwargs)
    
    class A(metaclass = Singleton):
        def __init__(self):
            self.aa = 1
    
    if __name__ == "__main__":
        a = A()
        b = A()
        print (id(a))
        print (id(b))
  • 相关阅读:
    cocos2d-x之物理引擎初试
    cocos2d-x之猜数字游戏
    cocos2d-x之加法计算器
    cocos2d-x之悦动的小球
    cocos2d-x之多个移动的小球
    cocos2d-x之json文件读取初试
    cocos2d-x之xml文件读取初试
    cocos2d-x之使用plist文件初试
    cocos2d-x之文件读写
    cocos2d-x之首选项数据初试
  • 原文地址:https://www.cnblogs.com/xiaobingqianrui/p/8435064.html
Copyright © 2020-2023  润新知