3月16日学习内容整理:单例模式的实现方法
一、单例模式的四种实现方法
1、基于文件(模块)导入实现
模块或者文件导入一次就不会被再次导入了
让模块再次导入的方法:
import db print(db.obj) import importlib importlib.reload(db)
2、基于类方法classsmethod,但是会改变调用方式,并且并发时就不是单例模式了所以得加锁
import threading import time class Foo(object): instance = None lock = threading.Lock() def __init__(self): self.a1 = 1 self.a2 = 2 import time import random time.sleep(2) @classmethod def get_instance(cls,*args,**kwargs): if not cls.instance: with cls.lock: if not cls.instance: obj = cls(*args,**kwargs) cls.instance = obj return cls.instance return cls.instance def task(): obj = Foo.get_instance() print(obj) import threading for i in range(5): t = threading.Thread(target=task,) t.start() time.sleep(10) Foo.get_instance()
3、基于_ _new_ _方法,不会改变调用方式,但是让要加锁
import threading import time class Foo(object): instance = None lock = threading.Lock() def __init__(self): self.a1 = 1 self.a2 = 2 import time import random time.sleep(2) def __new__(cls, *args, **kwargs): if not cls.instance: with cls.lock: if not cls.instance: obj = super(Foo,cls).__new__(cls,*args, **kwargs) cls.instance = obj return cls.instance return cls.instance def task(): obj = Foo() print(obj) for i in range(5): t = threading.Thread(target=task,) t.start()
4、基于metaclass
import threading lock = threading.Lock() class Singleton(type): def __call__(cls, *args, **kwargs): if not hasattr(cls, 'instance'): with lock: if not hasattr(cls,'instance'): obj = cls.__new__(cls,*args, **kwargs) obj.__init__(*args, **kwargs) setattr(cls,'instance',obj) return getattr(cls,'instance') return getattr(cls, 'instance') class Foo(object,metaclass=Singleton): def __init__(self): self.name = 'alex' obj1 = Foo() obj2 = Foo() print(obj1,obj2)