题
这是一个抽象工厂方法提供的值的正确方法
例如
interface IFactory
{
ISomething Create(int runTimeValue);
}
class Factory : IFactory
{
public ISomething Create(int runTimeValue)
{
return new Something(repository, runTimeValue);
}
}
在的例子中,存储库通过构造注入创建工厂时,但我可以代替移动存储库IFactory接口
interface IFactory
{
ISomething Create(IRepository repository, int runTimeValue);
}
class Factory : IFactory
{
public ISomething Create(IRepository repository, int runTimeValue)
{
return new Something(repository, runTimeValue);
}
}
什么被认为是这样做的“正确”的方式? 应该如何设计一个抽象工厂时,一个原因是什么?
解决方案
抽象工厂模式应在的情况下使用时由工厂需要返回的对象是“以这样的方式初始化”不同,只有厂家知道如何做到这一点。 ISomething的那么不同的实现将是“初始化”或创建的不同,只是各自的工厂实现知道如何做到这一点。
在你的情况,你要问自己:
待办事项 ISomethings的所有实施方式中所需要的IRepository以及runtimeValue ?.在这种情况下,你可以使用工厂模式。
使用抽象工厂在这样的场景:(有什么和SomeOtherthing创建不同)
interface IFactory {
ISomething Create(int runTimeValue);
}
class Factory : IFactory {
public ISomething Create(int runTimeValue) {
return new Something(repository, runTimeValue);
}
}
class OFactory : IFactory {
public ISomething Create(int runTimeValue) {
// constructor takes different parameters
SomeOtherthing thing = new SomeOtherthing("someValue", runtimeValue);
thing.SetCustomRepository(new OtherRepositoryImpl());
return thing;
}
}
其他提示
我会说是一致的。如果你的仓库被注入其他地方,它被使用,它将使意义它注入到工厂的构造函数,而不是使之成为界面的一部分。
不隶属于 StackOverflow