码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

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

标签:实现   single   技术分享   instance   targe   play   lan   get   模式   

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

 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

  

 

单例模式

标签:实现   single   技术分享   instance   targe   play   lan   get   模式   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!