python实现单例模式的几种方式

  1. 采用装饰器来建立单例模式

def singleton(cls):
    # 创建一个字典用来保存类的实例对象
    _instance = {}

    def _singleton(*args, **kwargs):
        # 先判断这个类有没有对象
        if cls not in _instance:
            _instance[cls] = cls(*args, **kwargs)  # 创建一个对象,并保存到字典当中
        # 将实例对象返回
        return _instance[cls]

    return _singleton

@singleton
class TestClass(object):
    a = 1

    def __init__(self, x=0):
        self.x = x
        self.a = x
        print('这是A的类的初始化方法')

    def show(self):
        print(self.x)
        print(self.a)
  1. 重写 new 方法的方式

class TestClass2(object):
    '''
    重写 __new__ 方法,让类创建的对象,在系统中只有唯一的一个实例
    '''
    # 记录第一个被创建对象的引用
    instance = None
    # 记录是否执行过初始化动作
    init_flag = False
    # 定义一个属性
    param = 0

    def __new__(cls, *args, **kwargs):

        # 1. 判断类属性是否是空对象
        if cls.instance is None:
            cls.instance = super().__new__(cls)
        return cls.instance

    def __init__(self, args=0):
        if not TestClass2.init_flag:
            print("初始化---")
            self.param = args
            TestClass2.init_flag = True

    def show(self):
        print(self.param)
  1. 采用多线程的方式


import threading

class TestClass3(object):

    _instance_lock = threading.Lock()
    param = 0
    param_dic = dict()

    def __init__(self, *args, **kwargs):
        pass

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            with TestClass3._instance_lock:
                if not hasattr(cls, '_instance'):
                    TestClass3._instance = object.__new__(cls)
                    cls.param = args[0]
                    cls.param_dic = kwargs
        return TestClass3._instance

    def show(self):
        print(self.param)
        print(self.param_dic)
  1. 测试方法

if __name__ == '__main__':

    # test1 = TestClass(2)
    # test2 = TestClass(3)
    # test1.show()
    # test2.show()

    # test3 = TestClass2(4)
    # test3.show()
    # test4 = TestClass2(5)
    # test4.show()

    # test5 = TestClass3(5, a=1, b='2', c=3)
    # test5.show()
    # test6 = TestClass3(6, a=1, b='2', c=3)
    # test6.show()
posted @ 2022-03-22 13:38  小泥巴2008  阅读(237)  评论(0编辑  收藏  举报