我试图弄清楚如何实现Apache Pool 2(我使用2.5)。作为初始POC,我使用firstName,lastName,employeeId和age(Observer Pattern)创建了一个Employee对象。我创建了一个实现PooledObjectFactory的EmployeeObjectFactory,在主类中我试图添加Employee类的对象。但是我得到了一个类转换异常(EmployeeObjects不能转换为PooledObjects)。那么我需要对EmployeeObjects进行哪些更改?
员工类
public class Employee{
private String firstName;
// omitting the getters and setters for other fields
public static class Builder {
private String firstName = "Unsub";
// declared and initialized lastName, emailId and age
public Builder firstName(String val) {
firstName = val;
return this;
}
// Similarly for other values
public EmployeeObject build() {
return new EmployeeObject(this);
}
}
private EmployeeObject(Builder builder) {
firstName = builder.firstName;
// omitting rest of the code
}
}
在EmployeeObjectFactory
中public class EmployeeObjectFactory implements PooledObjectFactory<EmployeeObject> {
@Override
public PooledObject<EmployeeObject> makeObject() {
return (PooledObject<EmployeeObject>) new EmployeeObject.Builder().build(); // This is where I'm getting the class cast
}
// Omitting rest of the code
}
主类
public static void main(String arg[]) throws Exception {
GenericObjectPool employeeObjectPool = new GenericObjectPool(new EmployeeObjectFactory());
employeeObjectPool.addObject();
我试图添加尽可能少的代码,因为即使我讨厌经历大量代码。任何帮助将不胜感激。
答案 0 :(得分:0)
阅读完Apache Docs后,终于得到了答案。 DefaultPooledObject是我需要使用的。 DefaultPooledObject - “创建一个包装所提供对象的新实例,以便池可以跟踪池化对象的状态。”在makeObject()函数中,我返回了一个DefaultPooledObject。所以我的代码看起来像
@Override
public PooledObject<EmployeeObject> makeObject() {
return new DefaultPooledObject<>(new EmployeeObject.Builder().build());
}