user2883072
user2883072

Reputation: 257

Creational pattern for generic objects

could someone please help with the best way of returning the concrete implementation in the following scenarios. Say I have:

public interface IThing<TInput> where TInput : RequestBase
{
    string Process(T input);
}

And then multiple implementations:

public class Thing1<T> : IThing<T> where T : ReqThing1
public class Thing2<T> : IThing<T> where T : ReqThing2

In my calling class what is the best way of wrapping the construction of those classes and returning the IThing that I want in a clean, testable way? Thanks

Upvotes: 0

Views: 32

Answers (1)

Gabriel Lima
Gabriel Lima

Reputation: 358

I don't quite understand what you want, but here's an idea:

public abstract class RequestBase
{
}

public class ReqThing1 : RequestBase
{
}

public class ReqThing2 : RequestBase
{
}

public interface IThing<T> where T : RequestBase
{
    string Process(T input);
}

public class Thing1 : IThing<ReqThing1>
{
    public string Process(ReqThing1 input)
    {
        throw new System.NotImplementedException();
    }
}

public class Thing2 : IThing<ReqThing2>
{
    public string Process(ReqThing2 input)
    {
        throw new System.NotImplementedException();
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var thing1 = new Thing1();
        var thing2 = new Thing2();
    }
}

Upvotes: 1

Related Questions