Python实现单例模式

Python单例模式

# Python单例模式示例1

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

class Foo(Singleton):
    num = 10

f1 = Foo()
f2 = Foo()
print(id(f1),f1)
print(id(f2),f2)


# Python单例模式示例2

class Singleton(object):
    one_instance = None
    def __new__(cls, *args, **kwargs):
        if not cls.one_instance:
            cls.one_instance = super(Singleton,cls).__new__(cls,*args,**kwargs)
        return cls.one_instance

f1 = Singleton()
f2 = Singleton()
print(id(f1),f1)
print(id(f2),f2)

  

Python基于线程安全的单例模式

# 线程安全的单例模式

import threading

class Singleton(object):
    INSTANCE = None
    lock = threading.RLock()
    def __new__(cls):
        cls.lock.acquire()
        if cls.INSTANCE is None:
            cls.INSTANCE = super(Singleton, cls).__new__(cls)
        cls.lock.release()
        return cls.INSTANCE

if __name__ == '__main__':
    a = Singleton()
    b = Singleton()
    print(id(a))
    assert id(a) == id(b)

  

# 装饰器实现

def make_synchronized(func):
    from threading import RLock
    func.__lock__ = RLock()
    def synced_func(*args, **kws):
        with func.__lock__:
            return func(*args, **kws)
    return synced_func

class Singleton(object):
    INSTANCE  =None
    @make_synchronized
    def __new__(cls, *args, **kwargs):
        if not cls.INSTANCE:
            cls.INSTANCE = super(Singleton,cls).__new__(cls,*args,**kwargs)
        return cls.INSTANCE

f1 = Singleton()
f2 = Singleton()
print(id(f1),f1)
print(id(f2),f2)

  

惰性初始化

参考:https://www.cnblogs.com/xybaby/p/6425735.html

单例模式的实现一般都有两种方式:

要么在调用之前就创建好单例对象(eager way),要么在第一次调用的时候生成单例对象(lazy way)

class eager_meta(type):
    def __init__(clz, name, bases, dic):
        super(eager_meta, clz).__init__(name, bases, dic)
        clz._instance = clz()

class singleton_eager(object):
    __metaclass__ = eager_meta

    @classmethod
    def instance(clz):
        return clz._instance


class singleton_lazy(object):
    __instance = None
    @classmethod
    def instance(clz):
        if clz.__instance is None:
            clz.__instance = singleton_lazy()
        return clz.__instance

  

 摘自:wiki

class Fruit:
    def __init__(self, item):
        self.item = item
    
class Fruits:
    def __init__(self):
        self.items = {}
    
    def get_fruit(self, item):
        if item not in self.items:
            self.items[item] = Fruit(item)
        
        return self.items[item]

if __name__ == '__main__':
    fruits = Fruits()
    print(fruits.get_fruit('Apple'))
    print(fruits.get_fruit('Lime'))

参考:https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python   *****

  

作者:Standby一生热爱名山大川、草原沙漠,还有妹子
出处:http://www.cnblogs.com/standby/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/standby/p/8179987.html