简体   繁体   中英

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.

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);

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.

The only usage i see would be when SimpleProvider implements interface with method Create(IContext context) . Then you could use it from classes that don't need to know the exact type of T which can be very important in some cases.

There is no practical difference if everything that you are saying is true, you just getting free type-safe method =)

It saves the caller having to necessarily know T during compilation time. It also keeps the interface consistent throughout the class hierarchy since the public method is decoupled from any specific subclass implementations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM