我想问一下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
}
我希望这可能会有所帮助(请阅读评论)
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
很好地为此服务),更高层更好地定义层接口实现并提供高层需要的服务。一个常见的错误是将这个原则与dependency injection相混淆,其中依赖关系通过更高级别提供给依赖类,而不是依赖类需要找到它们并创建它们。
看起来你似乎在询问依赖注入,这就是“我的依赖类如何得到我依赖的实例?”此示例看起来像属于同一域模型的这两个类,这意味着它们很可能位于同一模块中。让一个类依赖于另一个类并在同一个模块中直接创建它是一种合理的方法,但是随着类的发展,Factory pattern更加健壮。