单例模式

什么是单例模式

单例模式(也叫单件模式)的作用就是保证在整个应用程序的生命周期中,任何一个时刻,单例类的实例都只存在一个(当然也可以不存在)。

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()
  1. 基于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()

总结:单利模式存在的目的是保证当前内存中仅存在单个实例,避免内存浪费,在Django admin的源码中,就用到了单例模式!!!

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