C# 中的简单工厂设计从另一个工厂调用工厂?

Simple factory design in C# calling factory from another factory?

我需要在 C# 中创建一个带有简单工厂的对象,该对象有一个依赖对象,该对象也是使用另一个简单工厂创建的。

从另一个简单工厂调用一个简单工厂是不是一个好的设计原则?我想我可能在做一些奇怪的事情。

我有以下内容:

interface IObjecAtImplement {
    void task();
}

interface IObjecBtImplement {
    void taskFoo();
    void anotherTaskFoo();
}

public static class ObjectAFactory {

    public static IObjecAtImplement Get(string objecttype) {
        IObjectBImplement objectB = ObjectBFactory.Get(objecttype);
        switch (objecttype)
        case "A";
            return ObjectAFirstImplementacion(objectB);
        case "B";
            return ObjectASecondImplementacion(objectB);
    }
}

public static class ObjectBFactory {
    public static IObjecBtImplement Get(string objecttype) {    
        switch (objecttype)    
        case "A";
            return new ObjectBFirstImplementacion();
        case "B";
            return new ObjectBSecondImplementacion();
        }
    }
}

这是个好主意吗?还有其他解决方法吗? (代码括号没写好,只是举例)

您似乎在尝试将两种模式合二为一:factory and inversion of control。工厂负责对象的创建,而注入依赖通常是 IoC 容器的一个部门。

为了保持您 类 的明确职责,我建议考虑使用许多 IoC containers in .NET 之一。