Assuming you had some kind of factory-created resource that would still belong to the factory after construction like this:
public class Resource : IDisposable {
public void Dispose() { /* ... */ }
}
public class ResourceManager : IDisposable {
public Resource Load() { /* create resource and add to list */ }
public void Dispose() { /* dispose all loaded resources in list */ }
}
Now you have a base class that requires a Resource
instance in its constructor to initialize:
public class Fooificator {
public Fooificator(Resource resource) {
this.resource = resource;
}
private Resource resource;
}
How can a class that derives from such a base class construct a Resource
without loosing the reference to the factory?
The naive approach, using a static method, has no way of remembering the factory (except for ugly hacks like storing it in a static field for the constructor to pick up after base class construction finishes, or using a two-stage initialization where the Resource
is given to the base class through a constructor-called Initialize()
method)
public class DefaultFooificator : Fooificator {
public DefaultFooificator() : base(loadDefaultResource()) {}
private static Resource loadDefaultResource() {
ResourceManager resourceManager = new ResourceManager();
return resourceManager.Load();
// Bad: losing reference to ResourceManager here!
}
}
One possible workaround would be the named constructor idiom:
public class DefaultFooificator : Fooificator, IDisposable {
public static DefaultFooificator Create() {
ResourceManager resourceManager = new ResourceManager();
DefaultFooificator fooificator = new DefaultFooificator(
resourceManager.Load()
);
fooificator.resourceManager = resourceManager;
return fooificator;
}
private DefaultFooificator(Resource resource) : base(resource) {}
private ResourceManager resourceManager;
}
However, while solving the problem of storing the ResourceManager
reference, this will not allow for further classes to derive from the DefaultFooificator
.
Are there any elegant solutions that would enable me to further derive from DefaultFooificator
or to store the ResourceManager
reference in some other way?