Factory class returning a generic interface

Anish picture Anish · Nov 6, 2012 · Viewed 10.3k times · Source

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

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Nov 6, 2012

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