Sunny 软件公司开发人员欲创建一个数据库连接池,将指定个数的(如 2 个或 3 个)数据库连接对象存储在连接池中,客户端可以从池中随机取一个连接对象来连接数据库。试通过对单例类进行改造,设计一个能够自行提供指定个数实例对象的数据库连接类。
一、类结构图
连接池设计为单例,保证连接池的唯一性,它保持一个连接对象的 list 引用,每次从连接池获取连接对象的时候,随机从 list 中取出一个连接对象。
二、典型实现代码
连接池类:单例角色类
public class ConnectionPool {
private Integer connectionInitSize = 3;
private static volatile ConnectionPool connectionPool;
private List<Connection> connectionList = new ArrayList<>();
private ConnectionPool(Integer connectionInitSize) {
this.connectionInitSize = connectionInitSize;
for (int i = 0; i < connectionInitSize; i++) {
Connection connection = new Connection("连接" + i);
connectionList.add(connection);
}
}
private static ConnectionPool getInstance() {
if (connectionPool == null) {
synchronized (ConnectionPool.class) {
if (connectionPool == null) {
connectionPool = new ConnectionPool(3);
}
}
}
return connectionPool;
}
public static Connection getConnection() {
Integer nextInt = new Random().nextInt(getInstance().connectionInitSize);
return getInstance().connectionList.get(nextInt);
}
}
复制代码
连接类:
public class Connection {
private String name;
public Connection(String name) {
this.name = name;
}
public void doQuery() {
System.out.println(name + "开始连接");
}
}
复制代码
客户端代码:
public class Client {
public static void main(String[] args) {
Connection connectionA = ConnectionPool.getConnection();
Connection connectionB = ConnectionPool.getConnection();
Connection connectionC = ConnectionPool.getConnection();
connectionA.doQuery();
connectionB.doQuery();
connectionC.doQuery();
}
}
复制代码
编译并运行程序,输出的如下结果:
评论