是否有静态方法返回非单例类坏设计的类实例(例如id)?

时间:2015-03-03 05:58:24

标签: c# oop design-patterns

我对一位同事说,以下是糟糕的设计,但最后我无法给出任何理由(除了在这种情况下,已经有一个单身人士类被用作“集合”所有这些)。但一般情况下跟随有什么问题(只有“静态方法返回类的实例”-part,而不是如何处理例如interop。)这只是静态方法的一个例子,而不是真正的代码。

public class MyClass
{
    public int Id { get; private set; }
    /... other properties, constructors & methods

    // this is only static method
    public static GetMyClass(int id)
    {
        // get it in this case from unmanaged code
        return new MyClass(InteropThing.GetMyClassStruct(id));
    }
}

1 个答案:

答案 0 :(得分:3)

从示例代码看起来,您通过调用静态类隐藏了一个依赖项,这将使得模拟和单元测试变得尴尬。

也许更好的是:

public class MyClass
{
    private readonly IInteropThing _interop;

    public int Id { get; set; }

    public MyClass (IInteropThing interop)
    {
        _interop = interop;
    } 

    public GetMyClass(int id)
    {
        return new MyClass(_interop.GetMyClassStruct(id));
    }
}

看起来你可能违反了单一责任原则,这取决于MyClass正在做什么。

也许一个单独的类是唯一的功能是创建MyClass对象,这是一种更好的方法来促进松散耦合和可测试性。