jeudi 21 novembre 2019

What is the best design pattern to architecture this?

I have an architecture problem that I don't manage to solve alone.

  • I have a family of objects implementing the same interface (IThing).
  • I want to apply a transformation to each object of a collection of 'IThing'.
  • A transformation depends on the implementation of the interface.
  • A transformation for an implementation of the interface is encapsulated in a class. (Strategy Pattern)

My issue is that, somewhere, I always finish with a switch on type, or a set of if-is-cast, and to me it breaks the extensibility of my code.

Here is the exemple :

    public interface IThing
{
    string CommonProperty { get; }
}

public class FirstThing : IThing
{
    public string CommonProperty { get; }
    public string FirstParticularProperty { get; }
}

public class SecondThing : IThing
{
    public string CommonProperty { get; }
    public string SecondParticularProperty { get; }
}

public interface IThingTransformStrategy<T> where T : IThing
{
    string Transform(T thing);
}

public class FirstThingTransformStrategy : IThingTransformStrategy<FirstThing>
{
    public string Transform(FirstThing thing)
    {
        return thing.CommonProperty + thing.FirstParticularProperty;
    }
}

public class SecondThingTransformStrategy : IThingTransformStrategy<SecondThing>
{
    public string Transform(SecondThing thing)
    {
        return thing.CommonProperty + thing.SecondParticularProperty;
    }
}

public class ThingTransformer
{
    private FirstThingTransformStrategy _firstThingTransformStrategy = new FirstThingTransformStrategy();
    private SecondThingTransformStrategy _secondThingTransformStrategy = new SecondThingTransformStrategy();

    public string TransformThing(IThing thing)
    {
        //Here is the issue
        if (thing is FirstThing) return _firstThingTransformStrategy.Transform((FirstThing) thing);
        if (thing is SecondThing) return _secondThingTransformStrategy.Transform((SecondThing) thing);
        throw new NotImplementedException();
    }
}

Would you have any idea, or any pattern name in order to solve my problem ?

Thanks a lot.

Aucun commentaire:

Enregistrer un commentaire