Service factories

@Service(factory = MyFactory.class)
class MyService { ... }Last updated

@Service(factory = MyFactory.class)
class MyService { ... }Last updated
class MyFactory implements Factory<MyService, MyProperty> { ... }class MyFactory implements Factory<MyService, String> { ... }class MyFactory implements Factory<MyService, MyEnum> { ... }@Service(factory = CoolFactory.class)
interface AmazingService { ... }class CoolFactory implements Factory<AmazingService, String> { ... }void requestDependency() {
AmazingService service = Container.get(AmazingService, "EXAMPLE_PARAMETER");
}@Service(
// use the `CarFactory` class to create new instances for the `Car` type
factory = CarFactory.class,
// use `TRANSIENT` scope, to create a new car instance, each time a car
// is requested
scope = ServiceScope.TRANSIENT
)
interface Car {
void drive();
}
enum CarType {
MERCEDES,
BMW,
FERRARI
}
class CarFactory implements Factory<
Car,
CarType // you may specify any arbitrary factoryparameter type
> {
@Override
public @NotNull Car create(
@NotNull Service descriptor, @NotNull Class<? extends Car> type,
@NotNull Class<?> context, @Nullable CarType carType
) {
return switch (carType) {
case MERCEDES -> new MercedesCar();
case BMW -> new BMWCar();
case FERRARI -> new FerrariCar();
};
}
}
@Service
class CarDealership() {
public Car orderCar(CarType type) {
return Container.get(Car.class, type);
}
}
void orderCars() {
CarDealership dealership = Container.get(CarDealership.class);
assert dealership.orderCar(CarType.MERCEDES) instanceof MercedesCar;
assert dealership.orderCar(CarType.BMW) instanceof BMWCar;
assert dealership.orderCar(CarType.FERRARY) instanceof FerraryCar;
}