python如何实现单例模式

单例模式

单例模式是常见的软件设计模式,该模式主要目的确保某一个类只能有一个实例存在

1基于类注意:加锁否则多线程模式会报错

import time,threading

class Foo(object):
    lock = threading.Lock()
    def __init__(self):
        time.sleep(1)

    @classmethod
    def instance(cls,*args,**kwargs):
        if not hasattr(cls,'_instance'):
            with Foo.lock:
                if not hasattr(cls,'_instance'):
                    obj = cls(*args,**kwargs)
                    setattr(cls,'_instance',obj)
        return cls._instance

def func(arg):
    obj = Foo.instance()
    print(obj)

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

2基于new方法,也要加锁,原理同上

import threading,time
class Singleton(object):
    lock =  threading.Lock()

    def __init__(self):
        time.sleep(1)

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

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

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

3基于metaclass加锁,原理同上

class MyType(type):
    lock = threading.Lock()

    def __call__(cls, *args, **kwargs):
        if not hasattr(cls,'_instance'):
            with MyType.lock:
                if not hasattr(cls,'_instance'):
                    cls._instance = super(MyType,cls).__call__(*args, **kwargs)
        return cls._instance

class Foo(metaclass=MyType):
    def __init__(self):
        time.sleep(1)

def task():
    obj = Foo()
    print(obj)
for i in range(10):
    t = threading.Thread(target=task,)
    t.start()

4使用模块,python模块就是天然的单例模式,因为模块在第一次导入时会生成.pyc文件

1建立一个mysingleton的py文件
class my_Singleton(object):
      def foo(self)
          pass
my_singleton=my_Singleton()

将上面的代码保存在文件mysingleton.py中然后这样使用

from mysingleton import my_singleton
my_singleton.foo()
图片发自简书App
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。