Python单利实现

Python单利实现

在 Python 中,我们可以用多种方法来实现单例模式:

  • 使用模块
  • 使用 _new_
  • 使用装饰器(decorator)
  • 使用元类(metaclass)

使用模块

先在一个文件SingletonOne.py写入如下代码:

# SingletonOne.py中的代码
class SingletonOne(object):
    def foo(self):
        print("Hello SingletonOne")
        pass

singleton_one = SingletonOne()

使用方法是在另一个文件中如UseSingletonOne.py中导入使用

# 使用SingletonOne,UseSingletonOne.py
from SingletonOne import singleton_one

singleton_one.foo()

使用__new__

为了使类只能出现一个实例,我们可以使用 new 来控制实例的创建过程.

实现如下:

"""
在下面的代码中,我们将类的实例和一个类变量 _instance 关联起来,
如果 cls._instance 为 None 则创建实例,否则直接返回 cls._instance。
"""
class SingletonTwo:
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(SingletonTwo, cls).__new__(cls, *args, **kwargs)
        return cls._instance

class TestClss(SingletonTwo):
    a = 1


one = TestClss()
two = TestClss()
# 打印one和two的地址,是一样的
print(id(one), id(two))

使用装饰器(decorator)

实现如下:

"""
我们知道,装饰器(decorator)可以动态地修改一个类或函数的功能。
这里,我们也可以使用装饰器来装饰某个类,使其只能生成一个实例
"""

from functools import wraps

def singleton(cls):
    instance = {}
    @wraps(cls)
    def getInstance(*args, **kwargs):
        if cls not in instance:
            instance[cls] = cls(*args, **kwargs)
        return instance[cls]
    return getInstance

@singleton
class SingletonThree:
    a = 1

one = SingletonThree()
two = SingletonThree()
# 打印one和two的地址,是一样的
print(id(one), id(two))

使用元类metaclass

元类(metaclass)可以控制类的创建过程,它主要做三件事:

-拦截类的创建
-修改类的定义
-返回修改后的类

实现如下:

class SingletonFour(type):
    _instance = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instance:
            cls._instance[cls] = super(SingletonFour, cls).__call__(*args, **kwargs)
        return cls._instance[cls]

#ptyhon 2
# class TestSingletonFour:
#     __metaclass__ = Singleton


#python3
class TestSingletonFour(metaclass=SingletonFour):
    pass


one = TestSingletonFour()
two = TestSingletonFour()
# 打印one和two的地址,是一样的
print(id(one), id(two))

链接:https://github.com/Satelens/PythonSingleton
以上为四种python中单利实现方式,应该够用了。Have Fun!

猜你喜欢

转载自blog.csdn.net/houboye/article/details/79105705