cmo*_*moe 3 c# dependency-injection solid-principles
我一直在练习如何使用 SOLID 编写干净的代码。我还在代码中使用 DI 来消除耦合,但只能通过构造函数注入。在我使用过 DI 的很多情况下,我只是用它来调用方法。我还不明白的是,当您有一个依赖类,其构造函数在另一个类中接受参数时,如何解耦。如果var obj = new A(month)在 B 类内部创建依赖关系和紧密耦合,我如何解耦/抽象它?这就是属性接口的用武之地吗?如果是这样,我该如何在这里使用它?
public class A
{
private string _month;
public A(string month)
{
_month = month;
}
}
public class B
{
public List<A> ListOfMonths;
public B()
{
ListOfMonths = new List<A>();
}
public List<A> SomeMethod()
{
string[] months = new []
{
"Jan",
"Feb",
"Mar"
};
foreach(var month in months)
{
var obj = new A(month); // If this is coupling, how do I remove it?
ListOfMonths.Add(obj)
}
return ListOfMonths;
}
}
Run Code Online (Sandbox Code Playgroud)
如果要解耦,则需要从 B 中删除对 A 的任何引用,并用 IA(类似于 A 的接口)替换它们,IA 是任何将替换 A 的类的占位符。
然后,在 B 的构造函数中,您提供一个能够创建 IA 实例的工厂。您可以进一步放置一个抽象工厂,这意味着您提供了一个能够创建 IA 实例的工厂接口。
这是基于您的代码的示例:
public interface IA
{
}
public interface IAFactory
{
IA BuildInstance(string month);
}
public class AFactory : IAFactory
{
public IA BuildInstance(string month)
{
return new A(month);
}
}
public class A : IA
{
public A(string month)
{
}
}
public class B
{
private readonly IAFactory factory;
public List<IA> ListOfMonths;
public B(IAFactory factory)
{
this.factory = factory;
ListOfMonths = new List<IA>();
}
public List<IA> SomeMethod()
{
string[] months = new[] {"Jan", "Feb", "Mar"};
foreach (var month in months)
{
var obj = factory.BuildInstance(month);
ListOfMonths.Add(obj);
}
return ListOfMonths;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1700 次 |
| 最近记录: |