我有一个工厂类,它创建了几种不同类型的类。工厂在容器中注册。考虑到它们也有依赖关系,在工厂内创建类的推荐方法是什么。我显然想避免对容器的依赖,但如果我新建这些类,那么它们将不会使用容器。例如
public class MyFactory
{
public IMyWorker CreateInstance(WorkerType workerType)
{
if (workerType == WorkerType.A)
return new WorkerA(dependency1, dependency2);
return new WorkerB(dependency1);
}
}
所以问题是我从哪里获得这些依赖项。
一种选择是使它们成为工厂的依赖项。例如
public class MyFactory
{
private Dependency1 dependency1;
private Dependency2 dependency2;
public MyFactory(Dependency1 dependency1, Dependency2, dependency2)
{
this.dependency1 = dependency1; this.dependency2 = dependency2;
}
public IMyWorker CreateInstance(WorkerType workerType)
{
if (workerType == WorkerType.A)
return new WorkerA(dependency1, dependency2);
return new WorkerB(dependency1);
}
}
另一个可能是注册工人类型并建立工厂的依赖关系,例如
public class MyFactory
{
private IWorkerA workerA;
private IWorkerB workerB;
public MyFactory(IWorkerA workerA, IWorkerB, workerB)
{
this.workerA = workerA; this.workerB = workerB;
}
public IMyWorker CreateInstance(WorkerType workerType)
{
if (workerType == WorkerType.A)
return workerA;
return workerB;
}
}
对于第一个选项,我觉得我正在将工人的依赖关系吸进工厂。使用第二个选项,工人是在创建工厂时创建的。