I use the abstract factory pattern to add runtime dependencies to my object graph (that was created at program startup through a DI framework). Currently my factory stores all dependencies that I do have at compile-time. No I want to add some dependencies through a init() method at runtime. In my DI container I could spread the factory around my program and get the object by calling Factory#create()
.
Well, I could pass the runtime parameter at runtime (e.g. like Factory#create(String someString)
to avoid a leaky abstraction), however I only want to use the runtime parameter to finish the "set up" of the factory, so that I can get the object without providing any runtime parameters again?
Here a simple example for illustration:
public class CarFactory {
//can be injected at compile-time through DI container
Wheel wheel;
Light light;
public Car create(String carName) {
return new Car(carName, this.wheel, this.light);
}
}
At some point (and only there!) in the code [CodePosition1] I will get the runtime parameter, which I can use to finally build the car:
public class SomeClass {
CarFactory cf;
...
//thanks to the factory I can combine injectables and runtime params
Car car = cf.create("bmw");
...
}
However I want to use that newly created car also at other places, e.g. at a totally differnt [CodePosition2]:
public class CarConsumer() {
CarFactory carFactory;
...
//I want to get the car that same car I build at [CodePosition1] with
//something like the following as I don't have the runtime parameter here
Car car = carFactory.getCar();
...
}
The question is, where is the right place to "store" the new car from [CodePosition1] to use it at other places in the code, e.g. at [CodePosition2] or simply how to provide a dependency that was created at runtime still globally through the DI container? The factory only allows me to create an object where I can supply the runtime information.
The only solution I came up so far is to inject some sort of a context object, and fill this context object with runtime data. But this also leads to temporal coupling leaves the the object inside the context at null during compile time.