这篇“Python实现单例模式的方式有哪些”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Python实现单例模式的方式有哪些”文章吧。
简介:单例模式可以保证一个类仅有一个实例,并提供一个访问它的全局访问点。适用性于当类只能有一个实例而且客户可以从一个众所周知的访问点访问它,例如访问数据库、MQ等。
实现方式:
1、通过导入模块实现
2、通过装饰器实现
3、通过使用类实现
4、通过__new__ 方法实现
单例模块方式被导入的源码:singleton.py
# -*- coding: utf-8 -*-
# time: 2022/5/17 10:31
# file: singleton.py
# author: tom
# 公众号: 玩转测试开发
class Singleton(object):
    def __init__(self, name):
        self.name = name
    def run(self):
        print(self.name)
s = Singleton("Tom")主函数源码:
# -*- coding: utf-8 -*-
# time: 2022/5/17 10:51
# file: test_singleton.py
# author: tom
# 公众号: 玩转测试开发
from singleton import s as s1
from singleton import s as s2
# Method One:通过导入模块实现
def show_method_one():
    """
    :return:
    """
    print(s1)
    print(s2)
    print(id(s1))
    print(id(s2))
show_method_one()
# Method Two:通过装饰器实现
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 Demo2(object):
    a = 1
    def __init__(self, x=0):
        self.x = x
a1 = Demo2(1)
a2 = Demo2(2)
print(id(a1))
print(id(a2))
# Method Three:通过使用类实现
class Demo3(object):
    # 静态变量
    _instance = None
    _flag = False
    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    def __init__(self):
        if not Demo3._flag:
            Demo3._flag = True
b1 = Demo3()
b2 = Demo3()
print(id(b1))
print(id(b2))
# Method Four:通过__new__ 方法实现
class Demo4:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Demo4, cls).__new__(cls)
        return cls._instance
c1 = Demo4()
c2 = Demo4()
print(id(c1))
print(id(c2))运行结果: