Python3之实现单例模式de几种方式

来源:互联网 发布:天下3捏脸数据女妖艳 编辑:程序博客网 时间:2024/06/09 06:49

单例模式实现的几种方式

  1. 使用模块
  2. 使用__new__
  3. 使用装饰器
  4. 使用元类

使用模块

Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。

使用__new__

class Singleton:    def __new__(cls, *args, **kwargs):        if not hasattr(cls, '_instance'):            cls._instance = super().__new__(cls)        return cls._instances0 = Singleton()s1 = Singleton()print(id(s0))print(id(s1))

使用装饰器

from functools import wrapsdef singleton(cls):    instances = {}    @wraps(cls)    def getinstance(*args, **kwargs):        if cls not in instances:            instances[cls] = cls(*args, **kwargs)        return instances    return getinstance@singletonclass Bar:    passb0 = Bar()b1 = Bar()print(id(b0))print(id(b1))

使用元类

元类(metaclass)可以控制类的创建过程

class Singleton(type):    """    元类继承type    """    _instance = {}    def __call__(cls, *args, **kwargs):        if cls not in cls._instance:            cls._instance[cls] = super().__call__(*args, **kwargs)        return cls._instanceclass Bar(metaclass=Singleton):    passb0 = Bar()b1 = Bar()print(id(b0))print(id(b1))