Object Pooling with Generics

611 views Asked by At

I am trying to create a manager for object pools such that I can call a method from my manager in order to retrieve a reserved object in the pool or to create a new object when necessary. The objects to be pooled can vary greatly but must all inherit from a PooledObject class. There should never be any direct instance of the PooledObject class, only classes that extend PooledObject should be instantiated.

The problem is with the second portion, where I need to create a new object. I cannot instantiate a PooledObject as it is abstract, but including a new() constraint to the T generic does not allow Manager to instantiate the dictionary that manages the different PooledObjects. Below is a snippet of my code.

public class Manager{
    private Dictionary<Type, Pool<PooledObject>> _objects;

    public Manager()
    {
        _objects = new Dictionary<Type, Pool<PooledObject>>();
    }
    ...
}

public class Pool<T> where T : PooledObject{
    ...
    public T newObject(){
        ...
        var newT = new T(); // Error on this line
        ...
    }
    ...
}

public abstract class PooledObject{
    ...
}

How do I make it so that my generic T derives from a class that extends PooledObject and is not abstract so I can use the default constructor?

0

There are 0 answers