• Python中的单例模式


    单例模式(Singleton Pattern)是一种常用的软件设计模式。主要目的是确保某一个类只有一个实例存在。
    所以适用于类实例在__init__ 方法中不含有初始化参数的情况。

    实现方式

    __new__ 实现

    class Single:
        _instance = {}
    
        def __new__(cls, *args, **kwargs):
            if cls not in cls._instance:
                cls._instance[cls] = super().__new__(cls, *args, **kwargs)
            return cls._instance[cls]
    
        def say(self, a, b):
            print(a + b)
    
    
    c1 = Single()
    c2 = Single()
    
    print(id(c1))
    print(id(c2))
    print(c1 is c2)
    print(c1.say(1, 2) is c2.say(1, 2))
    

    函数装饰器实现

    def singleton_func(cls):
        _instance = {}
    
        def inner(*args, **kwargs):
            if cls not in _instance:
                _instance[cls] = cls(*args, **kwargs)
            return _instance[cls]
    
        return inner
    
    
    @singleton_func
    class Cls02:
        def say(self, a, b):
            print(a+b)
    
    
    cls1 = Cls02()
    cls2 = Cls02()
    print(id(cls1) == id(cls2))
    cls1.say(1, 2)
    

    metaclass 实现

    class SingletonCall(type):
        _instances = {}
    
        def __call__(cls, *args, **kwargs):
            if cls not in cls._instances:
                cls._instances[cls] = super().__call__(*args, **kwargs)
            return cls._instances[cls]
    
    
    class Cls4(metaclass=SingletonCall):
    
        def add(self, a, b):
            return a + b
    
    
    p1 = Cls4()
    p2 = Cls4()
    print(id(p1) == id(p2))
    print(p2.add(1, 2) is p1.add(1, 2))
    

    类装饰器实现

    class SingletonCls:
        def __init__(self, cls):
            self._cls = cls
            self._instance = {}
    
        def __call__(self, *args, **kwargs):
            if self._cls not in self._instance:
                self._instance[self._cls] = self._cls(*args, **kwargs)
            return self._instance[self._cls]
    
    
    @SingletonCls
    class Cls2(object):
        pass
    
    
    cls1 = Cls2()
    cls2 = Cls2()
    print(id(cls1) == id(cls2))
    
  • 相关阅读:
    c编写程序完成m名旅客和n辆汽车的同步程序代写
    [原]web服务器:SOAP,WSDL,UDDI
    用多进程同步方法演示“桔子-苹果”问题
    实验教学管理系统 c语言程序代写源码下载
    模拟游客一天的生活与旅游java程序代写源码
    Java作业代写
    快餐店运行模拟C++程序源码代写
    求可能组合VB源码代写
    深入源码分析Java线程池的实现原理
    ThreadLocal原理详解
  • 原文地址:https://www.cnblogs.com/jianjiacangcang/p/14950545.html
Copyright © 2020-2023  润新知