根据IoC和抽象工厂模式的类设计
问题描述:
哪种方法为抽象工厂方法提供值?根据IoC和抽象工厂模式的类设计
例如,
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);
}
}
什么被认为是这样做的“正确”的方式? 设计一个抽象工厂应该如何一个原因?
答
Abstract Factory pattern应该用于工厂返回的对象需要以不同的方式“初始化”,只有工厂知道如何去做。因此,不同的ISomething实现将被“初始化”或创建不同,并且只有它们各自的Factory实现方法才知道如何执行它。
你的情况,你要问自己:
做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;
}
}
答
我会说是一致的。如果您的资源库被注入到其他地方,那么将其注入到工厂的构造函数中而不是将其作为界面的一部分是有意义的。
谢谢,这有助于:) – Marcus 2010-08-10 16:55:59
你将如何测试这家工厂? OtherRepositoryImpl是一个具体的实现.... – danidacar 2014-08-12 12:49:38