0

为抽象工厂方法提供值的正确方法是什么?

例如。

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);
  }
}

什么被认为是“正确”的做法?设计抽象工厂时应该如何解释?

4

2 回答 2

0

我会说是一致的。如果您的存储库被注入到其他任何使用它的地方,那么将其注入工厂的构造函数而不是使其成为接口的一部分是有意义的。

于 2010-08-10T15:42:32.483 回答
0

抽象工厂模式应该用于工厂返回的对象需要以不同的方式“初始化”,只有工厂知道如何做的情况。因此 ISomething 的不同实现将被“初始化”或以不同方式创建,并且只有它们各自的工厂实现知道如何做到这一点。

在您的情况下,您必须问自己:

ISomethings 的所有实现都需要 IRepository 和 runtimeValue 吗在这种情况下,您可以只使用工厂模式。

在这种情况下使用抽象工厂:(Something 和 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;
  }
}
于 2010-08-10T15:36:42.430 回答