zoukankan      html  css  js  c++  java
  • java学习笔记-设计模式13(享元模式)

    意图

      运用共享技术有效地支持大量细粒度的对象。

      主要目的是实现对象的共享,即共享池,当系统中对象多的时候可以减少内存的开销,通常与工厂模式一起使用。

    public class ConnectionPool {  
          
        private Vector<Connection> pool;  
          
        /*公有属性*/  
        private String url = "jdbc:mysql://localhost:3306/test";  
        private String username = "root";  
        private String password = "root";  
        private String driverClassName = "com.mysql.jdbc.Driver";  
      
        private int poolSize = 100;  
        private static ConnectionPool instance = null;  
        Connection conn = null;  
      
        /*构造方法,做一些初始化工作*/  
        private ConnectionPool() {  
            pool = new Vector<Connection>(poolSize);  
      
            for (int i = 0; i < poolSize; i++) {  
                try {  
                    Class.forName(driverClassName);  
                    conn = DriverManager.getConnection(url, username, password);  
                    pool.add(conn);  
                } catch (ClassNotFoundException e) {  
                    e.printStackTrace();  
                } catch (SQLException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
      
        /* 返回连接到连接池 */  
        public synchronized void release() {  
            pool.add(conn);  
        }  
      
        /* 返回连接池中的一个数据库连接 */  
        public synchronized Connection getConnection() {  
            if (pool.size() > 0) {  
                Connection conn = pool.get(0);  
                pool.remove(conn);  
                return conn;  
            } else {  
                return null;  
            }  
        }  
    }  
    

      

      转自:http://blog.csdn.net/zhangerqing/article/details/8239539

  • 相关阅读:
    springcloud(三)
    springcloud(二)
    spring-cloud(一)
    springboot(三)
    springboot(二)
    springboot(一)
    dubbox
    SpringBoot终章(整合小型进销系统)
    SpringBoot第三节(thymeleaf的配置与SpringBoot注解大全)
    SpringBoot--集成Shiro
  • 原文地址:https://www.cnblogs.com/gxl00/p/5016501.html
Copyright © 2011-2022 走看看