2012-11-14 19 views
1

我正在嘗試使用apache commons pool來創建一個「對象」池。由於我已經有了一個對象工廠,它需要一個字符串類型參數並創建一個正確類型的對象,我想使用這個工廠。apache commons pool - 如何使用帶參數的工廠

但問題是沒有通用池對象的簽名允許我通過一個帶參數的工廠。

//This is a wrapper class that holds an Object pool 
Class INService { 

    private ObjectPool<INConnection> pool_ = null; 

    /** 
    * Constructs an instance of INService, given a pool size 
    * and a class which implements INHandler interface. 
    * @param poolSize - size of the service pool 
    * @param c - the class which handles the INHandler service interface. 
    */ 
    public INService(int poolSize, String objectType) { 

     pool_ = new GenericObjectPool<INConnection>(factory, Objecttype); // won't compile. 
    } 
    ... 
} 

的PoolableObjectfactory接口定義像makeObject,destroyObject,validateObject,activateObject和passivateObject方法。但是沒有帶參數的makeObject()方法。

看來,我能做到這一點的唯一方法是編寫多個工廠類,每種類型的對象,寫一個如果其他的東西,如:

public INService(int poolSize, String objectType) { 

     if (objectType.equals("scap") 
      pool_ = new GenericObjectPool<INConnection>(scapFactory); 
     else if (objectType.equals("ucip") 
      pool_ = new GenericObjectPool<INConnection>(ucipFactory); 
     ... 
    } 

或者,是否有任何優雅的方式,爲此而不是複製/創建幾個工廠類?

回答

2

您應該閱讀KeyedObjectPool<K,V>接口,該接口也可以在commons-pool中找到。

從它的javadoc:

A keyed pool pools instances of multiple types. Each type may be accessed using an arbitrary key. 

然後,您可以實現一個KeyedPoolableObjectFactory<K,V>基礎上,key參數進行的情況下,它具有makeObject(K key)功能,您正在尋找。

PS:看起來你並沒有將你的問題的答案標記爲「已接受」,你可能需要處理這個問題。

+0

你是如何設置keyPool的參數的?像這些: http://commons.apache.org/proper/commons-pool/api-1.2/org/apache/commons/pool/impl/GenericKeyedObjectPoolFactory.html – neoeahit

+1

@neoeahit我不記得我是否使用它其中一個[GenericKeyedObjectPoolFactory]的構造函數(http://commons.apache.org/proper/commons-pool/api-1.2/org/apache/commons/pool/impl/GenericKeyedObjectPoolFactory.html#constructor_summary)或通過[GenericKeyedObjectPool'的構造函數](http://commons.apache.org/proper/commons-pool/api-1.2/org/apache/commons/pool/impl/GenericKeyedObjectPool.html#constructor_summary),你必須嘗試。或者你想知道別的嗎? – JBert

相關問題