1、单例模式指的是创建单个实例,例如:数据库连接池中包含10个数据库连接,用户访问数据时随机从连接池中拿出一个进行连接,其他用户再次访问时不再创建对象进行连接

#!usr/bin/env python
# -*- coding:utf-8 -*-
class ConnecttionPool:
    __instance = None
    def __init__(self):
        self.ip = '222.133.177.67'
        self.port = '3306'
        self.username = 'odoo'
        self.password = '123456'

        self.con_list = [1,2,3,4,5,6,7,8,9,10]
    @staticmethod
    def get_instance():  #创建实例的方法
        if ConnecttionPool.__instance:
            return ConnecttionPool.__instance
        else:
            ConnecttionPool.__instance = ConnecttionPool()
            return ConnecttionPool.__instance
    def get_connection(self):
        #获得连接
        import random
        r = self.con_list[random.randrange(1,10)]
        return r

for i in range(10):
    pool = ConnecttionPool.get_instance()
    print('去连接池',pool,'获得一个连接')
    r = pool.get_connection()
    print('获得的连接是:',r)
单例模式

相关文章:

  • 2021-08-29
  • 2022-12-23
  • 2021-12-25
  • 2021-05-27
  • 2022-12-23
  • 2021-06-05
  • 2022-12-23
  • 2021-10-30
猜你喜欢
  • 2022-01-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-30
相关资源
相似解决方案