난 그냥 최근에 의존성 반전 원칙 및 제어의 반전에있어, 나는 현재 (내가 틀렸다면 정정 해줘) 알고에서 해당 DIP이다 한은 상태가의존성 삽입 (Dependency Injection) 문제
높은 수준의 모듈/클래스 저수준 모듈/클래스에 의존하지 않아야
높고 낮은 레벨의 모듈의 세부 사항에 의존하지 않아야 (되지이 하나 ??? 수단 무엇인지), 그러나 둘추상화 (인터페이스)
하지만 간단한 프로그램을 쓰고있을 때 이 원리를 구현하기 위해, 내가 (나중에 설명 할 것이다)
내 프로그램이 문제가 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);
}
을 "ICharacterable"을 구현하는 인벤토리 및 플레이어의 클래스로 구성
가 콘솔 (100) 을 대신 반환 문제에 달렸다 나는이 문제가 Player 대신 ICharacterable 유형을 주입한다고 선언했기 때문에 발생했음을 알았지 만 (어쨌든 DIP을 위반할 것입니다.) 어쨌든 제가 이것을 할 수 있습니까? 당신의 방법은 추가의 결과를 반환하고의 상태를 변경하지 때문에,
public int HealthIncrease(int health){
//increase health
return _health += health;
}
모델 정보가 아니라 "인벤토리 HAS-A 플레이어"가 이상하게 들립니다. 그리고 누가 물약, 선수 또는 재고품을 마십니까? –
왜 'HealthIncrease'가 아무 것도 반환하지 않습니까?나는 상태를 변경 (즉, 플레이어의 건강 분야를 향상)하거나 합계를 수행하고 반환합니다. 두 가지를 모두 수행하지는 않습니다. 이는 부작용입니다. – weston