单例模式
Posted 方杰0410
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例模式相关的知识,希望对你有一定的参考价值。
基于文件导入实现单例模式:
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
以上是关于单例模式的主要内容,如果未能解决你的问题,请参考以下文章