这里有一个场景:战士拿着刀去战斗:
刀:
class Sword { public void Hit(string target) { Console.WriteLine($"Chopped {target} clean in half."); } }
战士:
class Samurai { readonly Sword sword; public Samurai() { this.sword = new Sword(); } }
战士用刀:
public void Attack(string target) { this.sword.Hit(target); } }
OK,我们用刀武装了战士
分析:刀和战士是高内聚的,因为战士依赖刀才得以创建,当你想给战士换一个武器的时候,你必须修改战士的实现方法,即构造函数
武器接口:
interface IWeapon { void Hit(string target); }
继承接口的刀类:
class Sword : IWeapon { public void Hit(string target) { Console.WriteLine("Chopped {0} clean in half", target); } }
战士类:
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);
}
}
现在我们可以说:我们给战士注入了武器(构造函数注入),不需要修改战士的实现就能给他更换武器
原文:https://www.cnblogs.com/swobble/p/10643955.html