某软件公司开发人员要创建一个数据库连接池,将指定个数的(如两个或3个)数据库连接对象存储在连接池中,客户端代码可以从池中随机取一个连接对象来连接数据库。试通过对单例类进行改造,设计一个能够自行提供指定个数实例对象的数据库连接类并用Java代码中的懒汉式,饿汉式分别编程模拟。
时间: 2023-05-28 12:01:26 浏览: 49
1. 懒汉式:
```
public class ConnectionPool {
private static ConnectionPool connectionPool = null;
private List<Connection> connectionList;
private ConnectionPool(int count) throws SQLException {
connectionList = new ArrayList<Connection>();
for(int i=0; i<count; i++){
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "root");
connectionList.add(connection);
}
}
public static synchronized ConnectionPool getInstance(int count) throws SQLException {
if(connectionPool == null){
connectionPool = new ConnectionPool(count);
}
return connectionPool;
}
public synchronized Connection getConnection(){
if(connectionList.size() > 0){
return connectionList.remove(0);
}else{
return null;
}
}
public synchronized void close(Connection connection){
if(connection != null){
connectionList.add(connection);
}
}
}
```
2. 饿汉式:
```
public class ConnectionPool {
private static ConnectionPool connectionPool = new ConnectionPool(2);
private List<Connection> connectionList;
private ConnectionPool(int count) throws SQLException {
connectionList = new ArrayList<Connection>();
for(int i=0; i<count; i++){
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "root");
connectionList.add(connection);
}
}
public static ConnectionPool getInstance() {
return connectionPool;
}
public synchronized Connection getConnection(){
if(connectionList.size() > 0){
return connectionList.remove(0);
}else{
return null;
}
}
public synchronized void close(Connection connection){
if(connection != null){
connectionList.add(connection);
}
}
}
```