编程语言
首页 > 编程语言> > c# – 这是DIP(SOLID)的有效使用吗?

c# – 这是DIP(SOLID)的有效使用吗?

作者:互联网

我想问一下基因型和个体类的实现是否违反了依赖性倒置原则?如果是这样,如何解决?

这是代码:

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
}

解决方法:

我希望这可能会有所帮助(请阅读评论)

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的抽象类

标签:c,interface,abstraction,solid-principles,dependency-inversion
来源: https://codeday.me/bug/20190608/1200507.html