我最近还进入了依赖反转原理和控制反转,据我目前所知(如果我错了就纠正我),DIP声明:
高级模块/类不应依赖于低级模块/类。 高层和低级模块都不应该依赖于细节(不确定这意味着什么?),而应该依赖抽象(接口)。
但是当我编写一个实现这个原则的简单程序时,我遇到了一个问题(稍后会解释)。
我的程序由一个实现"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而不是130。我想问题是由于我宣布是注射ICharacterable类型而不是播放器造成的(但这会违反DIP),我可以这么做吗?谢谢
发布于 2016-12-24 13:08:48
结果很糟糕,因为您的方法只返回加法的结果,而不更改对象的状态。其他一切都是正确的。改为:
public int HealthIncrease(int health){
//increase health
_health += health;
return _health;
}你应该只考虑小替换,在我看来,播放器应该包含库存,而不是反之亦然。然后,您将遵循OOP设计模式,您的代码将更好。
高级模块/类不应依赖于低级模块/类。
在这种情况下,Player =高级级,库存=低级级。
高层和低级模块都不应该依赖于细节(不确定这意味着什么?),而应该依赖抽象(接口)。
快速解释:
抽象=接口或抽象类。很容易理解,这是您的ICharactable接口。
详细信息=实现。这是你的存货课。是什么使您的代码与此原则兼容。
发布于 2016-12-24 13:07:59
这不是依赖项注入问题,您只是在这里的代码中有一个bug:
public int HealthIncrease(int health){
//increase health
return _health += health;
}https://stackoverflow.com/questions/41313515
复制相似问题