【Python】 Python 中实现单例模式?

 在 Python 中,实现单例模式通常有多种方法。以下是使用类装饰器实现单例模式的方法:
```python
def singleton(cls):
    instances = {}
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance
@singleton
class MyClass:
    def __init__(self):
        self.value = 0
    def increment(self):
        self.value += 1
class AnotherClass:
    @staticmethod
    def my_static_method():
        print("This is a static method")
@singleton
class AnotherSingletonClass:
    def __init__(self):
        self.value = 0
    def increment(self):
        self.value += 1
# Test the singleton classes
if __name__ == "__main__":
    my_instance = MyClass()
    another_instance = AnotherClass()
    another_singleton_instance = AnotherSingletonClass()
    my_instance.increment()
    another_instance.my_static_method()
    another_singleton_instance.increment()
    print(my_instance.value)  # Output: 1
    print(another_instance is AnotherClass.my_static_method())  # Output: True
    print(another_singleton_instance.value)  # Output: 1
```
在这个例子中,我们定义了一个类装饰器 `singleton`,它接受一个类作为参数,并返回一个单例对象。`singleton` 装饰器使用字典 `instances` 来存储已经创建的实例。当我们尝试创建类的实例时,如果该类已经在 `instances` 字典中,则返回已有的实例;否则,创建新的实例并存储在 `instances` 字典中。
我们还定义了两个类 `MyClass` 和 `AnotherClass`,它们分别具有一个实例方法和静态方法。我们还定义了两个单例类 `MyClass` 和 `AnotherSingletonClass`,它们具有相同的实例方法和静态方法。
在测试部分,我们创建了 `MyClass`、`AnotherClass` 和 `AnotherSingletonClass` 的实例,并调用了它们的实例方法和静态方法。从输出中可以看出,`MyClass` 和 `AnotherSingletonClass` 的实例方法输出了相同的值,这是因为它们是同一个类的实例;而 `AnotherClass` 的静态方法输出了与 `AnotherSingletonClass` 的静态方法相同的输出,这是因为它们都是同一个类的静态方法。

相关推荐

  1. 【Python】 Python 实现模式

    2023-12-10 01:48:03       61 阅读
  2. 在 Python 实现模式

    2023-12-10 01:48:03       73 阅读
  3. 如何在PHP实现设计模式

    2023-12-10 01:48:03       65 阅读
  4. 【面试】在Python如何实现模式

    2023-12-10 01:48:03       48 阅读
  5. WPF 应用程序实现模式

    2023-12-10 01:48:03       60 阅读
  6. 在Python如何实现模式?

    2023-12-10 01:48:03       57 阅读
  7. Python的__new__方法及实现模式

    2023-12-10 01:48:03       23 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-10 01:48:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-10 01:48:03       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-10 01:48:03       82 阅读
  4. Python语言-面向对象

    2023-12-10 01:48:03       91 阅读

热门阅读

  1. Android 使用aapt工具获取apk信息

    2023-12-10 01:48:03       55 阅读
  2. 工业IC是什么

    2023-12-10 01:48:03       57 阅读
  3. 文件服务器搭建

    2023-12-10 01:48:03       64 阅读
  4. 类欧几里得算法

    2023-12-10 01:48:03       52 阅读
  5. openssl生成nginx ssl证书的简单方法

    2023-12-10 01:48:03       56 阅读
  6. 力扣面试150题 | 26.删除有序数组的重复项

    2023-12-10 01:48:03       69 阅读
  7. SQL注入原理及思路(mysql)

    2023-12-10 01:48:03       57 阅读
  8. 力扣labuladong一刷day32天二叉树

    2023-12-10 01:48:03       64 阅读
  9. 一步一步写线程之一简单的开始

    2023-12-10 01:48:03       52 阅读
  10. 如何设计自动完成系统

    2023-12-10 01:48:03       61 阅读