我一直在练习使用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;
}
}
_AAAFactory.Create(month)
代替new AAA(month)
。 - NeilB
在某种程度上充当了一个A
列表的工厂吗? - StackLloydB
的名称更改为AFactory
,并将SomeMethod
更改为Create
。这就是它所做的。 - Scott Hannen