• python基础之单例模式


    单例模式:

      什么是单例模式?

        基于某种方法实例化多次得到实例是同一个

      实现方法:

    ip = '1.1.1.1'
    port = 3306
    # 假装来自配置文件
    
    #方法一:定义类方法进行判断
    class Mysql:
        __instance = None
    
        def __init__(self, ip, port):
            self.ip = ip
            self.port = port
    
        @classmethod
        def from_settings(cls):
            if not cls.__instance:
                cls.__instance = cls(ip, port)
            return cls.__instance
    
    p1 = Mysql.from_settings()
    p2 = Mysql.from_settings()
    p3 = Mysql.from_settings()
    p4 = Mysql('1.1.3.2',2203)
    print(p1 is p2 is p3)  # Ture
    print(p1)
    print(p4)

    #方法二:使用装饰器
    def single(cls):
        _instance = cls(ip, port)
    
        def inner(*args, **kwargs):
            if len(args) + len(kwargs) == 0:
                return _instance
            return cls(*args, **kwargs)
        return inner
    
    @single
    class Mysql:
        __instance = None
    
        def __init__(self, ip, port):
            self.ip = ip
            self.port = port
    
    
    p1 = Mysql()
    p2 = Mysql()
    p3 = Mysql()
    p4 = Mysql('1.1.3.2',2203)
    print(p1 is p2 is p3) # True
    print(p1)
    print(p4)

    方法三:使用元类控制
    class Mymeta(type):
    def __init__(self,class_name,class_bases,class_dic):
    super().__init__(class_name,class_bases,class_dic)
    self.__instance = self.__new__(self)
    self.__init__(self.__instance,ip,port)

    def __call__(self, *args, **kwargs):
    if len(args) + len(kwargs) == 0:
    return self.__instance
    obj = self.__new__(self)
    self.__init__(obj,*args,**kwargs)
    return obj


    class Mysql(object,metaclass=Mymeta):
    __instance = None

    def __init__(self, ip, port):
    self.ip = ip
    self.port = port


    p1 = Mysql()
    p2 = Mysql()
    p3 = Mysql()
    p4 = Mysql('1.1.3.2',2203)
    print(p1 is p2 is p3) # True
    print(p1)
    print(p4)
     
  • 相关阅读:
    log4j日志输出级别(转)
    spring-framework——hao123
    gradle配置国内镜像
    项目启动控制台严重: Error listenerStart问题定位
    Pycharm按键失灵
    Mixed Content混合内容错误 Iframe Http页面无法访问
    RSA加密公钥系数获取结果多00
    xml报文标签替换正则表达式
    AES采用CBC模式128bit加密工具类
    js进行MD5加密(含中文),与后台JAVA加密之后结果不同(解决)
  • 原文地址:https://www.cnblogs.com/luck-L/p/9253754.html
Copyright © 2020-2023  润新知