先说下主要的类和接口
ObjectPool 接口是“池”定义,GenericObjectPool 是它的实现。
PooledObject 接口是“池对象”定义,DefaultPooledObject 是它的实现。
PooledObjectFactory 接口是“产生池对象的工厂”定义,BasePooledObjectFactory是它的实现。
下面我们先用以上几个类和接口搭建一个租车实例。
package com.pulsar.pool;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
public class CPool {
public static void main(String[] args){
CarFactory poolFactory = new CarFactory();
GenericObjectPool<Car> pool = new GenericObjectPool<>(poolFactory);
try {
Car car = pool.borrowObject();
System.out.println(car);
} catch (Exception e) {
e.printStackTrace();
}
}
static public class Car {
public String toString(){
return "BMW";
}
}
static public class CarFactory extends BasePooledObjectFactory {
@Override
public Object create() throws Exception {
return new DefaultPooledObject(new Car());
}
@Override
public PooledObject wrap(Object o) {
return (PooledObject)o;
}
}
}
来源:oschina
链接:https://my.oschina.net/bxnet/blog/4260860