Skip to content

FactoryProvider

Samuel Beausoleil edited this page Mar 22, 2022 · 2 revisions

The FactoryProvider aims to be the brain and glue between all the generators and factories in your application. It is not necessary to use one, but it is helpful to centralize all of your generators in the same object using an harmonized API. To create the provider of your application, it is highly recommended to use the FactoryProvider.make(Collection<Generator<?>>, DefaultKey, FactoryMaker<F>, boolean) static method to create it in an harmonious fashion. Using a dependency injection system such as Spring, it is recommended to let it initialize your individual generators, and then give them to this function in the following fashion:

// Create a provider in which all the generators of the application have been decorated in RecordingFactories
@Bean
public FactoryProvider<RecordingFactory<String, ?>> provider(List<Generator<?>> generators) throws IllegalAccessException {
    return FactoryProvider.make(generators,
                                FactoryProvider.DefaultKey.DEFAULT_KEY,
                                new RecordingFactoryMaker(),
                                true);
}

Usage

After creating your provider, you use it by specifying the class of object you want to create, then using the provided factory that can produce either the exact type, or if no factory can be found for exactly that type, the factory that produces the closest covariant type.

FactoryProvider<RecordingFactory<String, ?>> provider = FactoryProvider.make(
                generators,
                FactoryProvider.DefaultKey.DEFAULT_KEY,
                new RecordingFactoryMaker(),
                true);

// Create a regular city
City city = provider.factory(City.class).generate();
// Create a capital with 1M citizens
City capital = provider.factory(City.class).generate(CapitalGenerator.KEY, new FieldMod("nCitizens", 1_000_000L));
// Create an object (even though there is no explicit object generator)
Object obj = provider.factory(Object.class).generate();

Using make()

The Make() way of creating a provider takes 4 arguments:

  • Generators the list of generators this provider must handle
  • keyPolicy the policy of how to generate default keys for the new factories
  • factoryMaker how to transform each groups of generators that produce covariant types into a desired factory
  • replaceInnerReferences if true, the provider will modify the given generators so that they all refer to the new factories in their nested generators

Clone this wiki locally