这是 DIP (SOLID) 的有效使用吗?
Is this a valid use of DIP (SOLID)?
请问 类 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);
您不需要摘要 class 到 DIP
依赖倒置原则处理软件模块不一定classes。这个想法是,与其让高层依赖于低层的编码方式,不如让高层通过提供抽象 class (C# interface
服务来定义层接口更好这很好)让较低层实现和提供高层所需的服务。一个常见的错误是将此原则与 dependency injection 混淆,其中依赖项是由更高级别提供给依赖项 class,而不是依赖项 class 需要找到它们并创建它们。
你好像在问依赖注入,"how does my depending class get an instance of my dependency?"这个例子看起来像属于同一个领域模型的这两个 classes,这意味着它们很可能在相同的模块。让 class 依赖于另一个 class 并直接在同一个模块中创建它是一种合理的方法,但是 Factory pattern 随着 classes 的发展而更加健壮。
请问 类 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);
您不需要摘要 class 到 DIP
依赖倒置原则处理软件模块不一定classes。这个想法是,与其让高层依赖于低层的编码方式,不如让高层通过提供抽象 class (C# interface
服务来定义层接口更好这很好)让较低层实现和提供高层所需的服务。一个常见的错误是将此原则与 dependency injection 混淆,其中依赖项是由更高级别提供给依赖项 class,而不是依赖项 class 需要找到它们并创建它们。
你好像在问依赖注入,"how does my depending class get an instance of my dependency?"这个例子看起来像属于同一个领域模型的这两个 classes,这意味着它们很可能在相同的模块。让 class 依赖于另一个 class 并直接在同一个模块中创建它是一种合理的方法,但是 Factory pattern 随着 classes 的发展而更加健壮。