zoukankan      html  css  js  c++  java
  • CSIC_716_20191129【 单例模式 的五种实现方式】

     单例模式

    单例模式:在确定类中的属性和方法不变时,需要反复调用该类的情况。  让所有通过该类实例化出的对象,都指向同一个内存地址。

    优点:节省内存空间。

    单例模式有五种表现形式:

    1.通过classmethod实现

    2.通过__new__实现

    3.通过导入模块时实现

    4.通过装饰器实现

    5.通过元类实现

    1.通过classmethod实现

    classmethod单例开辟的空间中,最新的内容是第一次被更新的。之后的对象统一以最初的为准

    class Sun:
        __instance = None
    
        def __init__(self, ip, port):
            self.ip = ip
            self.port = port
    
        @classmethod
        def single(cls, ip, port):
            if not cls.__instance:
                cls.__instance = cls(ip, port)
    
            return cls.__instance
    
    
    obj1 = Sun.single('192.168.1.1', 9090)
    obj2 = Sun.single('127.0.0.1', 8080)
    obj3 = Sun.single('255.255.255.0', 7070)
    print(obj3.ip)  # 192.168.1.1
    print(obj2.ip)  # 192.168.1.1
    print(obj1.ip)  # 192.168.1.1
    

      

    2.通过__new__实现

     __new__单例开辟的空间中,最新的内容是最后一次被更新的。之前的对象统一以最新的为准.

    class Sun:
        __instance = None
    
        def __init__(self, ip, port):
            self.ip = ip
            self.port = port
    
        def __new__(cls, *args, **kwargs):  # 此处传入的参数只和类相关,其他的。
            if not cls.__instance:
                cls.__instance = object.__new__(cls)
    
            return cls.__instance
    
    
    obj1 = Sun('192.168.1.1', 9090)
    obj2 = Sun('127.0.0.1', 8080)
    obj3 = Sun('255.255.255.0', 7070)
    print(obj3.ip)  # 255.255.255.0
    print(obj2.ip)  # 255.255.255.0
    print(obj1.ip)  # 255.255.255.0
    

     

    3.通过元类实现单例模式

    元类单例开辟的空间中,最新的内容是第一次被更新的。之后的对象统一以最初的为准

    # _*_ coding: gbk _*_
    # @Author: Wonder
    class Singleton(type):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)  # 继承
            self._instance = None  # 派生
    
        def __call__(self, *args, **kwargs):
            if not self._instance:
                self._instance = super().__call__(*args, **kwargs)
            return self._instance  # 调用就返回
    
    
    class MySQL(metaclass=Singleton):
        def __init__(self, host, port):
            self.host = host
            self.port = port
    
    
    obj1 = MySQL('192.168.1.1', 9090)
    obj2 = MySQL('127.0.0.1', 8080)
    obj3 = MySQL('255.255.255.0', 7070)
    print(obj1.host)  # 192.168.1.1
    print(obj2.host)  # 192.168.1.1
    print(obj3.host)  # 192.168.1.1
    

      

     

  • 相关阅读:
    [Swift]LeetCode300. 最长上升子序列 | Longest Increasing Subsequence
    备忘录模式之C++实现
    leecode 题解 || Merge k Sorted Lists 问题
    数学三大危机
    singlefile.py
    Data Url生成工具之HTML5 FileReader实现
    算法题:打印1到最大的n位数
    java.lang.NoClassDefFoundError: org/apache/commons/lang/xwork/StringUtils
    hdu 1181 变形课
    postgis经常使用函数介绍(一)
  • 原文地址:https://www.cnblogs.com/csic716/p/11958418.html
Copyright © 2011-2022 走看看