Search code examples
c#classdesign-patternsderived

How to handle Derived Classes with overridden Generic Types in Lists?


I want to create a resource manager with customly typed derived resource classes like Texture1D, Texture2D, etc. Therefore I would like to override a generic type from the parent, so I`m able to return the resource data without casting it from object. (Also structs are possible with this solution).

See this approach if the text above was a little bit unclear:

I create an interface IResource. (1)
Then an abstract class implementing this interface. (2)
And finally my custom resource, which derives from Resource<T>. (3)

//1
public interface IResource : IDisposable

//2
// This class returns Data as T
public abstract class Resource<T> : IResource 

//3
// This class returns Data as GLEXTexture2D
public class Texture2DResource : Resource<GLEXTexture2D>

Basically, I have a ResourceManager with a List of IResource's which can add resources like this:

Texture2DResource resource = new Texture2DResource("a path", ResouceThreadAccess.LOCAL);
resourceManager.RegisterResource(resource);

Is this an acceptable design decision? In my oppinion the generic overriding code looks a bit confusing when creating new resources. Is there a better way to solve this tripple inheritance?


Solution

  • I often use the above pattern (ie: interface, with abstract base class, and the actual class itself). To answer if it is acceptable design decision, it depends on what you want to achieve (although generally it is a good design)...

    With resourceManager, you could loop through them and call the method in the interface (in which you can override as different implementation in the child object). This way, you don't even need to worry about casting from 'object'.

    However, if you have a lot of child-specific classes, which mean that from resourceManager you need to identify the specific child class -- then the 'generic' nature and abstract base class may not help as much.