Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please explain this pattern when using abstract method

I've seen the following pattern used in many places:

abstract class SimpleProvider<T> 
{
    public object Create(IContext context) 
    {
        return CreateInstance(context);
    }

    protected abstract T CreateInstance(IContext context);
}

I don't understand the practical difference, why is it not just written as:

abstract class SimpleProvider<T> 
{
    public abstract T Create(IContext context);
}

UPDATE: The above snippet it taken from the documentation for Ninject where no interface is specified, but looking at the actual source I can see that SimpleProvider<T> implements interface IProvider which explains the need for the sub-call and answers my question.

like image 754
fearofawhackplanet Avatar asked May 11 '26 02:05

fearofawhackplanet


2 Answers

So the only difference is the return type (Object instead of T), which would mean a cast is required by the caller.

The only reason I can think of to do this is if they were implemented an interface which had object Create(IContext context);

like image 165
Ray Avatar answered May 12 '26 16:05

Ray


It provides compile time type safety for the provider by ensuring that it creates an object of type T but allows the class to interface with more generic code that only works with objects.

This is pretty common when working with factory objects that are used with an inversion of control container.

like image 31
Chris Chilvers Avatar answered May 12 '26 16:05

Chris Chilvers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!