首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >这是DIP (固体)的有效使用吗?

这是DIP (固体)的有效使用吗?
EN

Stack Overflow用户
提问于 2016-04-29 10:06:39
回答 2查看 430关注 0票数 4

我想问的是,类GenotypesIndividual的实现是否违反了依赖反转原则?如果是的话,如何解决呢?

以下是代码:

代码语言:javascript
复制
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
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-04-29 10:45:46

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

代码语言:javascript
复制
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);

你不需要抽象类

票数 2
EN

Stack Overflow用户

发布于 2016-04-29 10:49:41

依赖反转原理处理的软件模块不一定是类。这样做的想法是,与其根据更低层次层的编码方式,更好的方法是为较低层提供一个抽象类( C# interface很好地服务于此)来定义层接口,以实现和提供高层所需的服务。一个常见的错误是将此原则与依赖注入混淆,在这种情况下,依赖关系是由更高级别提供给依赖类的,而不是需要查找和创建依赖类的类。

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36935471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档