Python实现单例模式的方式有哪些

发布时间:2022-05-18 11:07:46 作者:iii
来源:亿速云 阅读:127

这篇“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))

运行结果:

Python实现单例模式的方式有哪些

以上就是关于“Python实现单例模式的方式有哪些”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

推荐阅读:
  1. java单例模式的实现方式以及差异
  2. Kotlin中的单例模式有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:python怎么求解三角形第三边长

下一篇:jquery数据类型有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》