关于使用Python3实现单例模式

使用场景

当只需要创建一次对象,或者使用一个对象来对全局进行控制时,使用单例模式

懒汉式

饿汉式,更浪费一些资源,但是能保证线程安全

Python3 使用元类来创建,推荐!

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@Time    :   2023/05/11 21:56:56
@Author  :   sunqg 
@Desc    :   使用元类实现单例模式
'''

from typing import Any


class SingletonMeta(type):
    _instance = {}

    def __call__(cls, *args: Any, **kwds: Any) -> Any:
        if cls not in cls._instance:
            cls._instance[cls] = super.__call__(*args, **kwds)
        return cls._instance[cls]

class demo(metaclass=SingletonMeta):
    print("test")

if __name__ == '__main__':
    t1 = demo()
    t2 = demo()
    print(t1 is t2)
"""out
test
True
"""

你可能感兴趣的:(单例模式,python)