私はSOLID Principlesを学習しています。私は現在Dependency Injection and Interface Segregation Principlesに取り組んでいます。私はすでにこの2つの基本を持っていますが、それを組み合わせると混乱します。ここに私の実装では、私はSOLIDに「S」ルールなどの情報を表示するための別のクラスを作成した。..2つの異なるインタフェースを持つコンストラクタインジェクション(単一責任とインタフェース分離)
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());
}
}
のは、クラスは、行うことになっていないされてやるべきではないと述べています。そして、私はその情報を表示することはその仕事ではないと思います。私は今できweaponNameや損傷を持っている多くの武器を追加することができ、このインターフェースIWeaponで
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();
}
(私が間違っているなら、私を修正してください)。しかし、機能を追加した別の武器を追加したい場合は、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();
}
私の問題は、私は上記のDisplayPersonクラスにIWeaponv1を注入どうやっているのですか?それは可能か、ソリッド原則の私の理解は間違っていますか?私が間違っているか悪い練習をしたことが分かったら私を修正してください:)
をあなたはインタフェースではなく、継承を使用したほうが良いでしょう。例えば。 'IWeapon'の代わりに' public abstract class Weapon {} 'を追加しました。 –
あなたのコードのクラスは注射可能ではないnewablesだと思います。詳細については、この記事を参照してください。http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/ –
「DisplayPerson」を「サービス」に変換したい場合があります"PersonDisplayer"は武器と人物(newables)をメソッドパラメータとして持ち、依存関係ではありません。この記事をご覧ください:https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=99 –