我正在从这个来源学习构造函数注入https://softwareengineering.stackexchange.com/questions/177649/what-is-constructor-injection
我很高兴我能够理解它。但是,我对接口和类以及构造函数中的接口注入有一个基本的疑问。
具体来说,我无法理解我们如何在不创建第一个片段中的对象 Sword 的情况下注入接口。
class Samurai
{
readonly IWeapon weapon;
public Samurai()
{
this.weapon = new Sword();
}
public void Attack(string target)
{
this.weapon.Hit(target);
}
}
在下面的代码片段中,他们声称它与上面的代码做同样的事情,但是松耦合。
class Samurai
{
readonly IWeapon weapon;
public Samurai(IWeapon weapon)
{
this.weapon = weapon;
}
public void Attack(string target)
{
this.weapon.Hit(target);
}
}
有人可以帮我理解为什么我们没有"new"
在第二个片段中使用关键字创建 Sword 对象,以及它如何在没有它的情况下运行?以上两个片段是否相同?而且,这是如何失去耦合的?