I am learning SOLID Principles. I am working now with Dependency Injection and Interface Segregation Principles. I've already got the basics of this two but when I combined it, I got confused. Here's my implementation..
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());
}
}
I created another class for displaying information as "S" rule in SOLID says that a class shouldn't do which it is not supposed to do. And I think displaying that information is not its task. (Please correct me if I'm wrong)
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();
}
With this interface IWeapon, I can now able to add many weapons that have weaponName and damage. But if I want to add another weapon with added functions, we have to follow the ISP principle, right? So I created this interface and class below.
class Gun
{
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();
}
And I implemented it like this..
static void Main(string[] args)
{
DisplayPerson disp = new DisplayPerson(new Sword("Samurai Sword", 100), new Person("Jheremy", 19));
disp.DisplayAll();
Console.ReadKey();
}
My problem is how do I inject IWeaponv1 to DisplayPerson class above? Is it possible or my understanding in SOLID principles is just wrong. Please correct me if you see that I've done something wrong or bad practice :)
Aucun commentaire:
Enregistrer un commentaire