【发布时间】:2017-01-12 09:45:10
【问题描述】:
我正在学习 SOLID 原则。我现在正在使用依赖注入和接口隔离原则。我已经掌握了这两者的基础知识,但是当我将它们结合起来时,我感到困惑。这是我的实现..
class Person
{
public Person(string name, int age)
{
Name = name;
Age = age;
}
public string Name { get; set; }
public int Age { get; set; }
}
class DisplayPerson
{
private readonly IWeapon iwep;
private readonly Person pers;
public DisplayPerson(IWeapon iwep, Person perss)
{
this.iwep = iwep;
this.pers = perss;
}
public void DisplayAll()
{
Console.WriteLine("Name: " + pers.Name + "\nAge: " + pers.Age + "\n" + "Weapon: "
+ iwep.weaponName() + "\nDamage: " + iwep.damage().ToString());
}
}
我创建了另一个类来显示信息,因为 SOLID 中的“S”规则表示一个类不应该做它不应该做的事情。我认为显示这些信息不是它的任务。 (如有错误请指正)
class Sword : IWeapon
{
private string weaponNames;
private int damages;
public Sword(string weaponName, int damage)
{
this.weaponNames = weaponName;
this.damages = damage;
}
public string weaponName(){ return this.weaponNames; }
public int damage(){ return this.damages; }
}
public interface IWeapon
{
string weaponName();
int damage();
}
有了这个界面 IWeapon,我现在可以添加许多具有武器名称和伤害的武器。但是如果我想再添加一个具有附加功能的武器,我们必须遵循 ISP 的原则,对吗?所以我在下面创建了这个接口和类。
class Gun : IWeaponV1
{
private string weaponNames;
private int damages;
private int range;
public Gun(string weaponName, int damage, int range)
{
this.weaponNames = weaponName;
this.damages = damage;
this.range = range;
}
public string weaponName() { return this.weaponNames; }
public int damage(){ return this.damages; }
public int ranges() { return this.range; }
}
public interface IWeaponv1 : IWeapon
{
int range();
}
我是这样实现的..
static void Main(string[] args)
{
DisplayPerson disp = new DisplayPerson(new Sword("Samurai Sword", 100), new Person("Jheremy", 19));
disp.DisplayAll();
Console.ReadKey();
}
我的问题是如何将 IWeaponv1 注入到上面的 DisplayPerson 类中?有可能还是我对 SOLID 原则的理解是错误的。如果您发现我做错了什么或不正确的做法,请纠正我:)
【问题讨论】:
-
对于这种结构,最好使用继承而不是接口。例如。
public abstract class Weapon {}而不是IWeapon。 -
我认为你的代码中的类是newables而不是injectables。更多详情请看这篇文章:misko.hevery.com/2008/09/30/to-new-or-not-to-new
-
也许您想将
DisplayPerson转换为一个名为“PersonDisplayer”的“服务”,它将武器和人(newables)作为方法参数,而不是依赖项。看看这篇文章:cuttingedge.it/blogs/steven/pivot/entry.php?id=99
标签: c# design-patterns dependency-injection solid-principles single-responsibility-principle