依赖注入问题

Dependency Injection Problems

我最近才接触到依赖倒置原则和控制倒置,据我所知(如果我错了请纠正我)是 DIP 声明

high level module/class should not be dependent upon the low-level module/class

both high and low-level module should not depend on details(not sure what this one means???), but abstractions(interfaces)

但是我在写一个简单的程序来实现这个原理的时候,运行遇到了一个问题(后面会解释)

我的程序包含一个清单和实现“ICharacterable”的播放器class

      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);

}

问题是,控制台 returns 100 而不是 130。我认为问题是由于我声明注入的是 ICharacterable 类型而不是 Player(但这会违反 DIP ), 无论如何我可以做到这一点吗?谢谢

这不是依赖注入问题,您只是在此处的代码中存在错误:

   public int HealthIncrease(int health){
        //increase health
        return _health += health;

    }

你得到了不好的结果,因为你的方法只是 returns 添加的结果,而不是改变对象的状态。其他一切都是正确的。将其更改为:

public int HealthIncrease(int health){
    //increase health
    _health += health;
    return _health;
}

你应该只考虑小替换,在我看来Player应该包含Inventory,而不是相反。然后你会遵循OOP设计模式,你的代码会好很多。

high level module/class should not be dependent upon the low-level module/class

在这种情况下玩家 = 高等级class 和库存 = 低等级class

both high and low-level module should not depend on details(not sure what this one means???), but abstractions(interfaces)

快速解释:

抽象 = 接口或抽象class。很容易理解,就是你的 ICharactable 接口。

详情 = 实施。这是您的 库存 class。是什么让你的代码符合这个原则。