【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` 的静态方法相同的输出,这是因为它们都是同一个类的静态方法。

相关推荐
lolo大魔王2 分钟前
Go语言的反射机制
开发语言·后端·算法·golang
无风听海10 分钟前
Python类型守卫深度解析
python
那个失眠的夜16 分钟前
AspectJ
java·开发语言·数据库·spring
网域小星球35 分钟前
C++ 从 0 入门(四)|继承、多态、this 指针、深浅拷贝(C++ 面试终极收官)
开发语言·c++·面试·多态·继承·this指针·深浅拷贝
weixin_580614001 小时前
如何防止SQL注入利用存储过程_确保存储过程不拼字符串.txt
jvm·数据库·python
CoderYanger1 小时前
14届蓝桥杯省赛Java A 组Q1~Q3
java·开发语言·线性代数·算法·职场和发展·蓝桥杯
钮钴禄·爱因斯晨1 小时前
他到底喜欢我吗?赛博塔罗Java+前端实现,一键解答!
java·开发语言·前端·javascript·css·html
布说在见1 小时前
企业级 Java 登录注册系统构建指南(附核心代码与配置)
java·开发语言
草莓熊Lotso1 小时前
一文读懂 Java 主流编译器:特性、场景与选择指南
java·开发语言·经验分享
weixin_408717771 小时前
mysql权限表查询性能如何优化_MySQL系统权限缓存原理
jvm·数据库·python