python 单例模式

单例模式的解读:

该模式的主要目的是确保某一个类只有一个实例存在

应用示例:

如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信息。如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例,这就导致系统中存在多个 AppConfig 的实例对象,而这样会严重浪费内存资源,尤其是在配置文件内容很多的情况下。事实上,类似 AppConfig 这样的类,我们希望在程序运行期间只存在一个实例对象。

实现单例模式的几种方式

1.使用模块

其实,Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了

mysingleton.py

class Singleton(object):
    def foo(self):
        pass
singleton = Singleton()

将上面的代码保存在文件 mysingleton.py 中,要使用时,直接在其他文件中导入此文件中的对象,这个对象即是单例模式的对象

 

from mysingleton import singleton
singleton.foo()

2.使用装饰器

def Singleton(cls):
    instance = {}
    def _singleton(*args, **kargs):
        if cls not in instance:
            instance[cls] = cls(*args, **kargs)
        return instance[cls]
    return _singleton

@Singleton
class A(object):
    def __init__(self, x=0):
        self.x = x


a1 = A(2)
a2 = A(3)

 

3.基于__new__方法实现(推荐使用,方便)

我们知道,当我们实例化一个对象时,是先执行了类的__new__方法(我们没写时,默认调用object.__new__),实例化对象;然后再执行类的__init__方法,对这个对象进行初始化,所有我们可以基于这个,实现单例模式

 

# 示例一:
class Singleton(object):
    def __new__(cls,*args,**kwargs):
        if not hasattr(cls,"_instance"):
            orig=super(Singleton,cls)
            cls._instance=orig.__new__(cls,*args,**kwargs)
        return cls._instance
    
    
class MyClass(Singleton):
    a=1



# 示例二
import threading
class Singleton(object):
    _instance_lock = threading.Lock()

    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        if not hasattr(Singleton, "_instance"):
            with Singleton._instance_lock:
                if not hasattr(Singleton, "_instance"):
                    Singleton._instance = object.__new__(cls)
        return Singleton._instance

obj1 = Singleton()
obj2 = Singleton()
print(obj1,obj2)

def task(arg):
    obj = Singleton()
    print(obj)

for i in range(10):
    t = threading.Thread(target=task,args=[i,])
    t.start()

 

4.共享属性

 

创建实例时把所有实例的__dict__指向同一个字典,这样他们具有相同的属性和方法。


class BOrg(object):
    _state={}
    def __new__(cls,*args,**kwargs):
        ob=super(BOrg,cls).__new__(cls,*args,**kwargs)
        ob.__dict__=cls._state
        return ob

class MyClass(BOrg):
    a=1

 







 

posted @ 2020-05-29 23:03  乔小生1221  阅读(162)  评论(0编辑  收藏  举报