使用var + basic依赖工厂比C#接口更松散耦合吗?

Sea*_*man -1 c# oop var interface dynamic

这是一个一般性的设计问题.我们经常使用接口来解耦组件,写入接口而不是实现等.有时使用基本注入技术的接口,例如,

interface IMyInterface
{
    void DoSomething();
}

static class IMyInterfaceFactory
{
    public static IMyInterface GetInstance()
    {
        return new MyInterfaceInstance();
    }
}

class IMyInterfaceConsumer
{
    IMyInterface mInterface;

    public IMyInterfaceConsumer()
    {
        this.mInterface = IMyInterfaceFactory.GetInstance();
    }

    public void UseTheInterface()
    {
        this.mInterface.DoSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是关于使用var关键字.甚至没有使用真正的C#界面,但仍然在设计意义上创建一个"界面",

static class IMyInterfaceFactory
{
    // of course, this doesnt need to be a single instance
    static MyInterfaceInstance mSingleInstance; 

    // no longer programming to the interface, just returning the instance
    public static MyInterfaceInstance GetInstance()
    {
        // null coalesce
        return mSingleInstance ?? (mSingleInstance = new MyInterfaceInstance());
    }
}

class IMyInterfaceConsumer
{
    public void UseTheInterface()
    {
        // shorthand way, could also omit var, too 
        var myInterface = IMyInterfaceFactory.GetInstance();
        myInterface.DoSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)

这样我仍然只需要更改一次工厂,只要它返回的任何实例都支持需要消耗的方法,它就可以工作.然而,优点是生产和消费对象甚至不需要知道任何显式接口,也不存在.它还可以通过多种方法干净地支持接口(防止膨胀的接口声明).

一个明显的缺点是每次你想要从'interface'使用一个方法时,工厂可能不得不重新实例化该类,除非有一个缓存的单个实例(如上所述)或使用了一些memoization技术.

这种方法的优缺点是什么?这是一种常见做法吗?

Ben*_*igt 5

var关键字没有任何动态或松散的东西.它在编译时触发静态类型推断.

你的第二段代码与...相同

public void UseTheInterface()
{
    // shorthand way, could also omit var, too 
    MyInterfaceInstance myInterface = IMyInterfaceFactory.GetInstance();
    myInterface.DoSomething();
}
Run Code Online (Sandbox Code Playgroud)

工厂功能仍然是强类型的.实际上,通过删除界面,您可以使消费者代码更加紧密耦合.