1.MyDataSource implements DataSource---getConnection();
2.ConnectionWrapper implements Connection---close();
3.在getConnection()中用ConnectionWrapper对象做返回值,并传pool,con到wrapper中
思想:1)面向接口编程
2)装饰着模式---资源如何回收
1.定义类实现接口DataSource--getConnection()处理
MyDataSource implements DataSource{
//自定义10个大小的连接池,LinkedList去存储,用完不是真的销毁,而是放入到连接池
private static LinkedList<Connection> pool=new LinkedList<>();
static{
for(int i=0;i<10;i++){
pool.add(DBUtils.getConnection());
}
}
//在getConnection中
public Connection getConnection() throws SQLException {
Connection connection = pool.removeFirst(); //从集合中获取并删除
//装饰着模式 connection---ConnectionWrapper
ConnectionWrapper conWrapper=new ConnectionWrapper(connection,pool);
return conWrapper;
}
}
2.定义类实现接口Connection--close()处理:进行连接池回收
ConnectionWrapper implements Connection{
public void close() throws SQLException {
System.out.println("添加到连接池");
pool.add(connection); //连接池对象回收:把删除的连接对象添加到连接池
}
}
模拟连接池规范-DataSource
最新推荐文章于 2022-12-01 10:23:19 发布