简体   繁体   中英

Factory class returning a generic interface

I have few concrete which uses the following type of interface

interface IActivity<T>
{
    bool Process(T inputInfo);
}

Concrete classes are like as follows

class ReportActivityManager :IActivity<DataTable>
{
    public bool Process(DataTable inputInfo)
    {
        // Some coding here
    }
}

class AnalyzerActivityManager :IActivity<string[]>
{
    public bool Process(string[] inputInfo)
    {
        // Some coding here
    }
}

Now how can i write the factory class which retuns a generic interface some thing like IActivity.

class Factory
{
    public IActivity<T> Get(string module)
    {
        // ... How can i code here
    }
}

Thanks

You should create generic method, otherwise compiler will not know type of T in return value. When you will have T you will be able to create activity based on type of T :

class Factory
{
    public IActivity<T> GetActivity<T>()
    {
        Type type = typeof(T);
        if (type == typeof(DataTable))
            return (IActivity<T>)new ReportActivityManager();
        // etc
    }
}

Usage:

IActivity<DataTable> activity = factory.GetActivity<DataTable>();

Often this is implemented as in lazyberezovsky's answer . In c++ you could use template specialization to get compiler errors when you try to create a type the factory does not handle.

You can't do that in C# but you can get close. Though the code might look a little surprising which in turn could be a problem.

public static class Factory {
   public static IActivity<someType> Get(this someType self){
          //stuff specific to someType
   }

   public static IActivity<someOtherType> Get(someOtherType self){
          //stuff specific to someOtherType
   }

   public static T Creator<T>(){
        return null;
   }

}

The usage would then be

IActivity<someType> act = Factory.Creator<someType>().Get(); 

of course this only works if you can pass a concrete type. If you need to pass a type parameter things get more complicated.

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