基于文件导入实现单例模式:
db.py:
class Foo(object): def __init__(self): self.conn = "连接数据库" pass def get(self): self.conn obj = Foo() import redis obj = redis.Redis(host=‘10.211.55.4‘, port=6379)
views.py:
import db print(db.obj)
run.py:
import db import views print(db.obj)
基于 classmethod :
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()
基于__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) import threading for i in range(5): t = threading.Thread(target=task,) t.start()
基于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)
详细信息:https://www.cnblogs.com/huchong/p/8244279.html