...

Python设计模式-04-单例模式

单例模式是一种创建型设计模式,它保证一个类只有一个实例,并提供一个全局访问点。单例模式通常包括以下几个角色:

  • 单例(Singleton):定义了一个静态方法或类方法,用于获取单例对象。
  • 客户端(Client):使用单例对象来完成具体的操作。

下面是一个简单的 Python 示例,演示了如何使用单例模式创建一个只有一个实例的类:

class Singleton:
    __instance = None

    @classmethod
    def get_instance(cls):
        if cls.__instance is None:
            cls.__instance = cls()
        return cls.__instance

    def __init__(self):
        if self.__class__.__instance is not None:
            raise Exception('Singleton class cannot be instantiated more than once.')

singleton1 = Singleton.get_instance()
singleton2 = Singleton.get_instance()

print(singleton1 is singleton2)  # 输出 True

在上面的示例中,我们定义了一个单例类 Singleton,它包含一个静态方法 get_instance(),用于获取单例对象。在 get_instance() 方法中,我们首先检查类属性 __instance 是否为 None,如果是,则创建一个新的单例对象,并将其赋值给 __instance 属性。如果不是,则直接返回 __instance 属性。在单例类的构造函数中,我们使用self.__class__.__instance 来检查单例对象是否已经存在,如果已经存在,则抛出异常,防止单例类被实例化多次。

在使用单例模式时,我们可以通过调用单例类的静态方法 get_instance() 来获取单例对象。由于单例类只有一个实例,因此多次调用 get_instance() 方法会返回同一个对象。需要注意的是,单例模式可能会导致全局状态的存在,因此需要谨慎使用。

posted @ 2023-06-16 18:11  韩志超  阅读(105)  评论(0编辑  收藏  举报