Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 687
Anish Avatar asked Nov 06 '12 11:11

Anish


1 Answers

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>();
like image 118
Sergey Berezovskiy Avatar answered Nov 15 '22 00:11

Sergey Berezovskiy