我有一个关于松散耦合和接口的概念/理论问题。
所以使用接口的一种方法可能是封装某个构造函数所需的参数:
class Foo
{
public Foo(IFooInterface foo)
{
// do stuff that depends on the members of IFooInterface
}
}
所以只要传入的对象实现了契约,一切都会工作。据我了解,这里的主要好处是它支持多态性,但我不确定这是否真的与松散耦合有关。
让我们说一个 IFooInterface 如下:
interface IFooInterface
{
string FooString { get; set; }
int FooInt { get; set; }
void DoFoo(string _str);
}
从松散耦合的角度来看,不要在上面的构造函数中使用 IFooInterface 会更好,而是像这样设置 Foo :
class Foo
{
public Foo(string _fooString, int _fooInt, Action<string> _doFoo)
{
// do the same operations
}
}
因为说我想把 Foo 的功能放到另一个项目中。这意味着其他项目也必须引用 IFooInterface,添加另一个依赖项。但是这样我可以将 Foo 放到另一个项目中,它准确地表达了它需要什么才能工作。显然我可以只使用重载的构造函数,但是为了论证的缘故,我不想和/或不能修改 Foo 的构造函数。
最显着的缺点(至少对我而言)是,如果您有一个带有一堆原始参数的方法,它会变得丑陋且难以阅读。所以我有了创建一种包装函数的想法,它允许您仍然传递接口而不是所有原始类型:
public static Func<T, R> Wrap<T, R>(Func<T, object[]> conversion)
{
return new Func<T, R>(t =>
{
object[] parameters = conversion(t);
Type[] args = new Type[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
args[i] = parameters[i].GetType();
}
ConstructorInfo info = typeof(R).GetConstructor(args);
return (R)info.Invoke(parameters);
});
}
这里的想法是,我可以取回一个函数,该函数采用符合 Foo 要求的某个接口的实例,但 Foo 实际上对该接口一无所知。它可以像这样使用:
public Foo MakeFoo(IFooInterface foo)
{
return Wrap<IFooInterface, Foo>(f =>
new object[] { f.FooString, f.FooInt, f.DoFoo })(foo);
}
我听说过关于接口应该如何启用松散耦合的讨论,但对此感到疑惑。
想知道一些有经验的程序员是怎么想的。