mercredi 5 octobre 2022

Factory that should return different types based on input param

I have type based on which I need to create different objects. The one specific thing - all that object has some common part.

So I thought to have some base class for them. And in each separate class add only specific properties.

class BaseClass {
    public int Prop1 {get;set;}
    public string Prop2 {get;set;}
}

class MyClass1 : BaseClass {
    public int PropMyClass1 {get;set;}
}

class MyClass2 : BaseClass {
    public string PropMyClass2 {get;set;}
}

I thought about create factories:

interface ICreator<T>{
    bool CanHanlde(string type);
    T Create();
}

class Creator1: ICreator<MyClass1>
{
    bool CanHandle(string type) {return "type1" == type;}
    MyClass1 Create();
}

class Creator2: ICreator<MyClass2>
{
    bool CanHandle(string type) {return "type2" == type;}
    MyClass2 Create();   
} 

And now I would like to create some factory that will return concreate class based on type. Problem - I don't know how to pass type into generic. From where I need to get type? I can register all types for ICreator and inject it with DI. Select the one which return true in CanHandle method. But don't know how to get type for generic.

Aucun commentaire:

Enregistrer un commentaire