views:

32

answers:

2

Hi,

Which is the correct way of providing values to a abstract factory method?

Eg.

interface IFactory
{
  ISomething Create(int runTimeValue);
}

class Factory : IFactory
{
  public ISomething Create(int runTimeValue)
  {
    return new Something(repository, runTimeValue);
  }
}

In the example the repository is injected via the constructor when factory is created but I could instead move the repository to the IFactory interface

interface IFactory
{
  ISomething Create(IRepository repository, int runTimeValue);
}

class Factory : IFactory
{
  public ISomething Create(IRepository repository, int runTimeValue)
  {
    return new Something(repository, runTimeValue);
  }
}

What is considered "correct" way of doing this? How should one reason when designing an abstract factory?

A: 

Abstract Factory pattern should be used in cases when the objects returned by the factory need to be "initialized" differently in such a way that only the factory knows how to do it. So different implementations of ISomething will be "initialized" or created differently and only their respective Factory implementations know how to do it.

In your case you have to ask yourself:

Do all implementations of ISomethings need the IRepository as well as runtimeValue?. In that case you can just use the factory pattern.

Use Abstract Factory in such a scenario: (Something and SomeOtherthing are created differently)

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;
  }
}
naikus
Thanks, this helps :)
Marcus
A: 

I'd say be consistent. If your repository is injected everywhere else that it is used, it would make sense to inject it into the factory's constructor rather than making it a part of the interface.

mlaw