首页 > 其他 > 详细

单例模式

时间:2018-04-06 23:23:33      阅读:187      评论:0      收藏:0      [点我收藏+]

基于文件导入实现单例模式:

 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)
View Code

 views.py:

技术分享图片
import db


print(db.obj)
View Code

 run.py:

技术分享图片
import db
import views

print(db.obj)
View Code
基于 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()
View Code

基于__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()
View Code

基于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)
View Code

详细信息:https://www.cnblogs.com/huchong/p/8244279.html

  

 

单例模式

原文:https://www.cnblogs.com/fangjie0410/p/8729265.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!