• 23种设计模式学习之享元模式


    典型:各种连接池

        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;  
                }  
            }  
        }  
    
  • 相关阅读:
    668. Kth Smallest Number in Multiplication Table
    658. Find K Closest Elements
    483. Smallest Good Base
    475. Heaters
    454. 4Sum II
    441. Arranging Coins
    436. Find Right Interval
    410. Split Array Largest Sum
    392. Is Subsequence
    378. Kth Smallest Element in a Sorted Matrix
  • 原文地址:https://www.cnblogs.com/2nao/p/8297224.html
Copyright © 2020-2023  润新知