私は最近、依存性逆転原理と制御の反転に入った、と私は現在、(私が間違っているなら、私を修正)知っているから、そのDIPできましたが述べている依存性注入問題
ハイレベルのモジュール/クラス(この1つは?何を意味するかわからない)の詳細に依存するべきではないハイ及びローレベルのモジュールの両方低レベルモジュール/クラス
に依存すべきではないが、抽象化(インターフェイス)
しかし、私が単純なプログラムを書いていたときこの原則を実装するために、私はこの問題に遭遇した(後で説明します)
私のプログラムに問題がある「ICharacterable」
class Player : ICharacterable {
private int _health = 100;
public int Health{
get{
return _health;
}
}
public int HealthIncrease(int health){
//increase health
return _health + health;
}
}
class Inventory{
ICharacterable player = null;
//constructor injection
public Inventory(ICharacterable player) {
this.player = player;
}
//increase player health
public void UseHealthPotion(int health) {
player.HealthIncrease(health);
}
}
class Program{
static void Main(string[] args) {
Player john = new Player();
Inventory inv = new Inventory(john);
inv.UseHealthPotion(30);
Console.WriteLine(john.Health);
}
}
//interface
public interface ICharacterable {
int HealthIncrease(int health);
}
を実装インベントリとプレイヤーのクラスで構成され、コンソールではなく、100を返します。私は、問題はPlayerの代わりにICharacterable型を注入していると宣言したという事実が原因であると考えています(しかし、それはDIPに違反します)とにかく私はこれを行うことができますか?あなたの方法でのみ加算の結果を返し、状態を変更しないので、
public int HealthIncrease(int health){
//increase health
return _health += health;
}
サイドモデルではなく、「インベントリHAS-A Player」が奇妙に聞こえます。そして誰が飲料、選手、在庫を飲むのでしょうか? –
なぜ 'HealthIncrease'は何かを返しますか?私は状態を変更する(つまり、プレイヤーの健康フィールドを上げる)か、合計を実行して返すかのどちらかを行いません。それは副作用です。 – weston