Factory class returning a generic interface

10,687

Solution 1

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

Solution 2

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.

Share:
10,687
Anish
Author by

Anish

Updated on June 05, 2022

Comments

  • Anish
    Anish almost 2 years

    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