简体   繁体   中英

Object pool: abstract super-class or generic?

In my project, I want to use object pool for different types of objects — with similar behavior, but different pool sizes.

Should I create generic class for a pool and interface to apply to created objects, or should I create abstract pool class with common logic and then create specific sub-classes for all the different classes that I want to use it with?

Well you can have both things ie create an abstract generic class. I would prefer a generic interface implemented by a generic class and instantiated for a specific type behind a factory method/class. Abstract class will force creating derived classes making it more tedious. The example usage that I have in mind are something like

IPool<MyClass> = PoolFactory.Get<MyClass>(5);  // 5 being pool size
IPool<IFoo> = PoolFactory.Get<FooImpl>(5);
IPool<IBar> = PoolFactory.Get(5, () => new BarImpl("some argument")); // instance creation with factory method

Note that it can still leave me a scope for specialization by inheriting from the generic class - typical need would be a complicated instance creation (of course can be modeled by supplying the pool implementation with factory interface or factory delegate)

That is the typical scenario for generic types. So I advocate generic pool.

Generics make only problems in cases where other classes use references to it without knowing the concrete type. In that case you can create a non-generic interface that is implemented by generic pool class.

This is a classic example of why you should prefer Generic Stack<T> over object based Stack class and why generics was introduced to solve the object based classes problem. This is explained in MSDN here .

I suppose if you use second option, then you would have to introduce a new concrete class for every object pool that you want to create in future which would be cumbersome to maintain and develop . So, go with the first option of creating a Generic Pool<T> class and yes, you can also avail the benefits of Factory design pattern with this first option as explained in another answer.

In fact, there is a sample Generic ObjectPool<T> implementation here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM