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

これを行う「正しい」方法とは何ですか?抽象ファクトリを設計するときの1つの理由は何ですか?

4

2 に答える 2

0

ファクトリによって返されるオブジェクトを、ファクトリだけがその方法を知っているような方法で「初期化」する必要がある場合は、抽象ファクトリパターンを使用する必要があります。したがって、ISomethingのさまざまな実装は「初期化」されるか、さまざまに作成され、それぞれのFactory実装のみがその方法を知っています。

あなたの場合、あなたは自分自身に尋ねなければなりません:

ISomethingsのすべての実装には、 runtimeValueだけでなくIRepositoryも必要ですか?その場合は、ファクトリパターンを使用できます。

このようなシナリオではAbstractFactoryを使用します:(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 に答える
0

一貫していると思います。リポジトリが使用されている他のすべての場所に注入される場合は、それをインターフェイスの一部にするのではなく、ファクトリのコンストラクタに注入する方が理にかなっています。

于 2010-08-10T15:42:32.483 に答える