2016-04-29 50 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会更加健壮。