2016-04-29 83 views
4

我想問一下,類GenotypesIndividual的實現是否違反了依賴倒置原則?如果是這樣,如何解決這個問題?這是DIP(SOLID)的有效用法嗎?

classes-abstraction hierarchy

下面是代碼:

public interface IGenotype 
{ 
    //some code... 
} 

public abstract class AIndividual 
{ 
    // ... some code 
    public IGenotype Genotype { get; set;} // DIP likes that ! 
} 

public class Individual : AIndividual 
{ 
    public Individual() 
    { 
     // some code ... 
     this.Genotype = new Genotype(); // Is this ok in case of DIP? 
    } 
} 

public class Genotype : IGenotype 
{ 
    // ... some code 
} 

回答

2

我希望這可以幫助(請閱讀評論)

public interface IGenotype 
{ 
    //some code... 
} 

public class Genotype : IGenotype 
{ 
    // ... some code 
} 

public class Individual 
{ 
    // Here, instead of depending on a implementation you can inject the one you want 
    private readonly IGenotype genotype; 

    // In your constructor you pass the implementation 
    public Individual(IGenotype genotype) 
    { 
     this.genotype = genotype; 
    } 
} 

// Genotype implements IGenotype interface 
var genotype = Genotype(); 

// So here, when creating a new instance you're injecting the dependecy. 
var person = Individual(genotype); 

你不需要的抽象類DIP

2

依賴倒置原理處理軟件模塊不一定是類。這個想法是,取決於低層圖層編碼的高層圖層,更高層通過提供一個抽象類(一個C#interface可以很好地服務於這個圖層)來更好地定義層接口,實現並提供高層所需的服務。一個常見的錯誤是將此原則與dependency injection混淆,其中依賴關係是由更高級別提供給依賴類的,而不是依賴類需要找到它們並創建它們。

看來你問的是依賴注入,即「我的依賴類如何獲得我的依賴項的實例?」這個例子看起來像這兩個屬於同一個域模型的類,這意味着它們很可能在同一個模塊中。讓一個類依賴於另一個類並直接在同一個模塊中創建它是一種合理的方法,但隨着類的發展,Factory pattern會更加健壯。