zoukankan      html  css  js  c++  java
  • 单例模式

    单例模式

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

    当实例化多次得到的对象中存放的属性都一样的情况,应该将多个对象指向同一个内存,即同一个实例

    单例模式(类内部定义静态方法)

    # settings.py
    IP = '1.1.1.1'
    PORT = 3306
    
    
    class Mysql:
        __instacne = None
    
        def __init__(self, ip, port):
            self.ip = ip
            self.port = port
    
        @classmethod
        def from_conf(cls):
            if cls.__instacne is None:
                cls.__instacne = cls(IP, PORT)
            return cls.__instacne
    
    
    obj1 = Mysql.from_conf()
    obj2 = Mysql.from_conf()
    obj3 = Mysql.from_conf()
    
    print(obj1 is obj2 is obj3)
    ####
    True
    
    
    print(obj1.__dict__)
    print(obj2.__dict__)
    print(obj3.__dict__)
    ####
    {'ip': '1.1.1.1', 'port': 3306}
    {'ip': '1.1.1.1', 'port': 3306}
    {'ip': '1.1.1.1', 'port': 3306}
    
    
    obj4 = Mysql('10.10.10.11', 3307)
    print(obj4.__dict__)
    ####
    {'ip': '10.10.10.11', 'port': 3307}
    

    单例模式(装饰器)

    # settings.py
    IP = '1.1.1.1'
    PORT = 3306
    
    
    def singleton(cls):
        cls.__instance = cls(IP, PORT)
    
        def wrapper(*args, **kwargs):
            if len(args) == 0 and len(kwargs) == 0:
                return cls.__instance
            return cls(*args, **kwargs)
    
        return wrapper
    
    
    @singleton  # Mysql = singleton(Mysql) # Mysql = wrapper
    class Mysql:
        def __init__(self, ip, port):
            self.ip = ip
            self.port = port
    
    
    obj1 = Mysql()  # wrapper()
    obj2 = Mysql()  # wrapper()
    obj3 = Mysql()  # wrapper()
    
    print(obj1 is boj2 is obj3)
    #####
    True
    
    
    print(obj1.__dict__)
    print(obj2.__dict__)
    print(obj3.__dict__)
    #####
    {'ip': '1.1.1.1', 'port': 3306}
    {'ip': '1.1.1.1', 'port': 3306}
    {'ip': '1.1.1.1', 'port': 3306}
    
    
    obj4 = Mysql('1.1.1.4', 3308)
    print(obj4.__dict__)
    #{'ip': '1.1.1.4', 'port': 3308}
    
    print(obj1 is obj2 is obj3)
    ###
    True
    
    
    print(obj1.__dict__)
    print(obj2.__dict__)
    print(obj3.__dict__)
    #####
    {'ip': '1.1.1.1', 'port': 3306}
    {'ip': '1.1.1.1', 'port': 3306}
    {'ip': '1.1.1.1', 'port': 3306}
    
    
    obj4 = Mysql('1.1.1.4', 3308)
    print(obj4.__dict__)
    #####
    {'ip': '1.1.1.4', 'port': 3308}
    
  • 相关阅读:
    呃,如何使 .NET 程序,在 64位 系统 中,以 32位 模式运行。
    [转载]Cortana 设计指导方针
    Could not load file or assembly System.Core, Version=2.0.5.0
    wpf中用户控件的属性重用
    浅谈AutoResetEvent的用法
    WPF异步载入图片,附带载入中动画
    WPFLoading遮层罩
    获取WPF的DataGrid控件中,是否存在没有通过错误验证的Cell
    WPF通过异常来验证用户输入
    WPF验证之——必填验证
  • 原文地址:https://www.cnblogs.com/zhoajiahao/p/11068096.html
Copyright © 2011-2022 走看看