4

我想问一下类的实现是否Genotypes违反Individual了依赖倒置原则?如果是这样,如何解决?

类抽象层次

这是代码:

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
}
4

2 回答 2

3

依赖倒置原则处理软件模块不一定是类。这个想法是,与其根据较低层的编码方式来决定较高层,不如让较高层通过提供一个抽象类来定义层接口(C#interface很好地服务于这一点)供较低层实现并提供高层需要的服务。一个常见的错误是将此原则与依赖注入混淆,其中依赖项由更高级别提供给依赖类,而不是依赖类需要找到它们并创建它们。

您似乎在询问依赖注入,即“我的依赖类如何获取我的依赖实例?” 这个例子看起来像这两个属于同一个领域模型的类,这意味着它们很可能在同一个模块中。让一个类依赖于另一个类并直接在同一个模块中创建它是一种合理的方法,但是随着类的发展,工厂模式更加健壮。

于 2016-04-29T10:49:41.857 回答
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

于 2016-04-29T10:45:46.343 回答