美文网首页python学习Python常用模块
python如何实现单例模式

python如何实现单例模式

作者: _Caesar | 来源:发表于2018-04-01 19:17 被阅读28次

单例模式

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

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()
python如何实现单例模式

相关文章

  • Python经典面试题21道

    1、Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例子使用了不同的方式实现单例模...

  • Python最经典面试题21道,必看!

    1、Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例子使用了不同的方式实现单例模...

  • Python 经典面试题

    1、Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例子使用了不同的方式实现单例模...

  • Python 经典面试题

    1、Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例子使用了不同的方式实现单例模...

  • 一套完整Python经典面试题,实力派,做内容不做标题党!

    文末含Python学习资料 1:Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例...

  • python面试题-2018.1.30

    问题:如何实现单例模式? 通过new方法来实现单例模式。 变体: 通过装饰器来实现单例模式 通过元类来创建单例模式...

  • 2018-06-19 Python中的单例模式的几种实现方式的及

    转载自: Python中的单例模式的几种实现方式的及优化 单例模式 单例模式(Singleton Pattern)...

  • python必知必会10

    如何用 Python 实现单例模式? 单例模式在很多地方都存在争议,但是,它作为一种最简单和使用广泛的设计模式。 ...

  • 基础-单例模式

    单例模式总结-Python实现 面试里每次问设计模式,必问单例模式 来自《Python设计模式》(第2版) 1.理...

  • python单例模式

    python单例模式实现方式 使用模板 python模块是天然的单例模式(.pyc文件的存在) 使用__new__...

网友评论

    本文标题:python如何实现单例模式

    本文链接:https://www.haomeiwen.com/subject/unjocftx.html