mardi 13 novembre 2018

Is the factory design pattern applicable in this situation

  • taskA, taskB, taskC inherit from my class Task

  • ContextA, ContextA2, ContextB, ContextC inherit from my class Context

Contexts have a corresponding Task as class property.

When iterating over a list of tasks, I want to create the corresponding Context :

foreach (Task t in tasks)
{
    Context context;

    if (t is TaskA)
    {
        if (condition)
        {
            context = new ContextA() { Task = t as TaskA};
        }
        else
        {
            context = new ContextA2() { Task = t as TaskA };
        }
    }
    else if (t is TaskB)
    {
        context = new ContextB() { Task = t as TaskB };
    }
    else if (t is TaskC)
    {
        context = new ContextC(){ Task = t as TaskC };
    }
    else
    {
        throw new Exception("Unkown Task");
    }

    context.CommonProperty = "value";
    context.CallOverriddenMethod();//Do different things based on the context type
}

I feel there should be a cleaner way to achieve this but I can't figure out how to manage the creation of the context object, especially the case of contextA and contextA2 that depend on a condition.

Aucun commentaire:

Enregistrer un commentaire