Search code examples
c#genericsmemory-managementabstract-classobjectpool

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?


Solution

  • Well you can have both things i.e 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)