工厂设计模式是否适用于这种情况

时间:2018-11-13 15:34:40

标签: c# oop design-patterns

  • taskA,taskB,taskC从我的Task类继承

  • ContextA,ContextA2,ContextB,ContextC从我的类Context继承

上下文具有相应的Task作为类属性:

public abstract class Context
{
    public String CommonProperty { get; set; }

    public abstract void MethodToOverride();
}

public class ContextA : Context
{
    public TaskA Task { get; set; }

    public override void MethodToOverride()
    {
        //do stuff with this.Task and this.CommonProperty
    }
}

public class ContextA2 : Context
{
    public TaskA Task { get; set; }

    public override void MethodToOverride()
    {
        //do stuff with this.Task and this.CommonProperty
    }
}

public class ContextB : Context
{
    public TaskB Task { get; set; }

    public override void MethodToOverride()
    {
        //do stuff with this.Task and this.CommonProperty
    }
}

依此类推...

遍历任务列表时,我想创建相应的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.MethodToOverride();//Do different things based on the context type
}

我认为应该有一种更干净的方法来实现这一目标,但是我无法弄清楚如何管理上下文对象的创建,尤其是取决于条件的contextA和contextA2的情况。

2 个答案:

答案 0 :(得分:0)

ui

我真的不喜欢传递这种条件,在我看来,这是一种代码味道,但是从您所说的来看,它必须是任务之外的东西。无论如何,这应该可以满足您的需求

答案 1 :(得分:0)

是的,适合工厂模式。

class ContextFactory {
    public create(TaskA t, bool condition) {
        return condition ? new ContextA() { Task = t } : new ContextA2() { Task = t };
    }
    public create(TaskB t) {
        return new ContextB() { Task = t };
    }
    public create(TaskC t) {
        return new ContextC() { Task = t };
    }
}
...
ContextFactory factory = //... new or passed from somewhere
foreach (Task t in tasks) {
    Context context;
    if (t is TaskA) {
        context = factory.create(t as TaskA, condition);
    } else if (t is TaskB) {
        context = factory.create(t as TaskB);
    } else if (t is TaskC)
        context = factory.create(t as TaskC);
    } else {
        throw new Exception("Unkown Task");
    }
    context.CommonProperty = "value";
    context.MethodToOverride();//Do different things based on the context type
}