Rou*_*hof 5 .net encapsulation dependency-injection
假设我有一个PetManager和一个Cat:
class PetManager
{
PetManager(IBusinessLayer businessLayer, IWashingService washingService);
IBusinessLayer BusinessLayer;
IWashingService WashingService;
}
class Cat
{
Cat(PetManager manager, string name, int levelOfStupidity);
}
Run Code Online (Sandbox Code Playgroud)
现在让我们说,我的猫需要洗衣服,要从我的宠物经理那里得到抚养费,它是如此地难道吗?
class Cat
{
Cat(PetManager manager, string name, int levelOfStupidity)
{
this.manager = manager;
this.name = name;
this.levelOfStupidity = levelOfStupidity;
}
IWashingService WashingService
{
get { return this.manager.WashingService; }
}
}
Run Code Online (Sandbox Code Playgroud)
我强烈怀疑是的,这可能是...
如前所述,Cat 是一个具体的类,因此它可以公开任何有意义的内容。将构造函数参数公开为只读属性是一件非常明智的事情。
然而,如果 Cat 实现了 ICat,我会强烈怀疑通过 ICat 公开像 PetManager 这样的依赖项将是一个有漏洞的抽象。
本质上,接口充当一种访问修饰符。公开对具体类的依赖关系是有意义的,但对接口的依赖关系则不然。依赖项是通过构造函数注入的,因此永远不能成为接口的一部分 - 构造函数签名是我们的自由度。