Pregunta

¿Cuál es la forma correcta de proporcionar valores a un método de fábrica abstracto?

Ej.

interface IFactory
{
  ISomething Create(int runTimeValue);
}

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

En el ejemplo el repositorio se inyecta a través del constructor cuando se crea fábrica, pero en lugar de eso se podía mover el repositorio a la IFactory interfaz

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

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

¿Qué se considera una forma "correcta" de hacer esto? ¿Cómo debería una razón en el diseño de una fábrica abstracta?

¿Fue útil?

Solución

patrón Abstract Factory debe utilizarse en casos en los que los objetos devueltos por la necesidad fábrica para que sea " inicializado" de manera diferente de tal manera que sólo la fábrica sabe cómo hacerlo. Así que diferentes implementaciones de ISomething serán "inicializar" o crean de forma diferente y sólo sus respectivas implementaciones de fábrica saben cómo hacerlo.

En el caso de que tenga que preguntarse:

Do todos implementaciones de ISomethings necesita el IRepository, así como runtimeValue ?. En ese caso, sólo puede utilizar el patrón de la fábrica.

Uso Abstract Factory en este escenario: (Algo SomeOtherthing y se crean de forma diferente)

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

Otros consejos

Yo diría que sea consistente. Si el depósito se inyecta en cualquier otro lugar que se utiliza, lo que tendría sentido para inyectarlo en el constructor de la fábrica en lugar de lo que es una parte de la interfaz.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top