python-单例模式示例用法

  • Post author:
  • Post category:python




单例定义及优点


  • 单例模式

    (Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。


    也就是说 多次实例化的结果指向同一个内存地址 ,无论产生多个对象,都会指向 单个 实例


  • 使用单例优点:

    节省内存



python使用单例

	1.通过classmethod
    2.通过装饰器实现
    3.通过__new__实现
    4.通过导入模块时实现
    5.通过元类实现。



通过classmethod 实现

class Test:

	# 一个默认值,用于判断对象是否存在, 对象不存在证明值是None
    # __instance是类的属性,可以由类来调用
    __instance = None

    @classmethod
    def singleton(cls):
        if not cls.__instance:
	        # 产生一个对象并返回
            obj = cls()
            # None ---> obj
            cls.__instance = obj
            
     	# 若__instance中有值,证明对象已经存在,则直接返回该对象
        return cls.__instance

t1 = Test.singleton()
t2 = Test.singleton()
print(t1)  # <__main__.Test object at 0x000002376E916BC8>
print(t2)  # <__main__.Test object at 0x000002376E916BC8>



通过__new__


class Test1:

    __instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            # 造一个空对象
            cls.__instance = object.__new__(cls)
        return cls.__instance

t1 = Test1()
t2 = Test1()
print(t1)  # <__main__.Test1 object at 0x000001F8088C8F48>
print(t2)  # <__main__.Test1 object at 0x000001F8088C8F48>



通过装饰器实现

  • 无参数形式
# 无参数形式
def singleton(cls):
    _instance = {}

    def inner(*args, **kwargs):
        if cls not in _instance:
            obj = cls(*args, **kwargs)
            _instance[cls] = obj
        return _instance[cls]
    return inner


@singleton
class Test2:  # Test2 =singleton(Test2)  Test2=inner
    pass

t1 = Test2()  # inner()
t2 = Test2()
print(t1)
print(t2)
  • 带参数形式
def singleton(cls):
    _instance = {}

    def inner(*args, **kwargs):
        if cls not in _instance:
            obj = cls(*args, **kwargs)
            _instance[cls] = obj
        return _instance[cls]
    return inner


@singleton
class Test2:  # Test2 =singleton(Test2)  Test2=inner
    def __init__(self, x, y):
        self.x = x
        self.y = y

t1 = Test2(1,2)
t2 = Test2(3,4)
print(t1)
print(t2)



通过导入模块

通过导入模块:

Singleton.py

class Father:
    pass
obj = Father()

单例模式.py
from Singleton import obj
print(obj)
from Singleton import obj
print(obj)
from Singleton import obj
print(obj)



版权声明:本文为qq_41390161原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。