假设我们在一个与数据库交互的系统中,需要进行数据库操作,那么我们就有必要了解单例模式,单例模式使得我们不用每次进行数据库的操作时都去链接数据库。

我将循环渐进,由浅入深的写一下单例模式示例。

实例1:

db.py

class Foo(object):
    def __init__(self):
        self.conn = "连接数据库"

    def get(self):
        return self.conn

obj = Foo()

views.py

import db

print(db.obj)

run.py

import db
import views

print(db.obj)

执行run.py,打印结果如下,这就是单例模式

<db.Foo object at 0x000001C1D8FC5A58>
<db.Foo object at 0x000001C1D8FC5A58>

实例二:

注意这里使用了锁来解决线程安全问题

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()

实例三:

import threading

class Foo(object):
    instance = None
    lock = threading.Lock()

    def __init__(self):
        self.a1 = 1
        self.a2 = 2
        import time
        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() 

实例四:

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)

  

最新文章

  1. stm32新建工程详细步骤
  2. SQL Server删除重复行的6个方法
  3. 【OSG】osgText::Text 研究
  4. hdu 1087
  5. preventDefault() 方法 取消掉与事件关联的默认动作
  6. poj 2104 K-th Number - 经典划分树
  7. Problem 2169 shadow
  8. C#_会员管理系统:开发二(会员资料管理界面的‘增删改查’)
  9. Unity3D方法来隐藏和显示对象
  10. Linux shell 脚本(一)
  11. List GroupBy真实用法,Reflection(反射)用法,Enum用法,正则,搜索下拉布局
  12. 第一篇-Win10打开txt文件出现中文乱码
  13. 【Jmeter】api性能测试总结
  14. Metasploit 简单渗透应用
  15. JavaScript 第七章总结
  16. prime docker-compose 环境运行试用
  17. 【树】Construct Binary Tree from Preorder and Inorder Traversal
  18. 【Android】3.5 示例5--多地图展示
  19. 自创open vp n windows步骤
  20. Netty框架

热门文章

  1. 20145204 《Java程序设计》第9周学习总结
  2. 学习Zookeeper之第2章Zookeeper安装
  3. Python学习札记(二十二) 函数式编程3 filter &amp; SyntaxError: unexpected EOF while parsing
  4. UVa 10534 波浪子序列(快速求LIS)
  5. hdu 1004 Let the Balloon Rise strcmp、map、trie树
  6. Codeforces 909C Python Indentation:树状数组优化dp
  7. 一个产生临时图片Url的地方
  8. Python小工具之消耗系统指定大小内存
  9. 深入理解javascript之typeof和instanceof
  10. URAL 1106 Two Teams (DFS)