FactoryModuleBuilder (Guice latest API)
public final class FactoryModuleBuilder extends java.lang.Object
Provides a factory that combines the caller's arguments with injector-supplied values to construct objects.
Defining a factory
Create an interface whose methods return the constructed type, or any of its supertypes. The method's parameters are the arguments required to build the constructed type.public interface PaymentFactory { Payment create(Date startDate, Money amount); }You can name your factory methods whatever you like, such as create, createPayment or newPayment.
Creating a type that accepts factory parameters
constructedType
is a concrete class with an @Inject
-annotated constructor. In addition to injector-supplied parameters, the constructor should have parameters that match each of the factory method's parameters. Each factory-supplied parameter requires an @Assisted
annotation. This serves to document that the parameter is not bound by your application's modules. public class RealPayment implements Payment { @Inject public RealPayment( CreditService creditService, AuthService authService, @Assisted Date startDate, @Assisted Money amount) { ... } }
Multiple factory methods for the same type
If the factory contains many methods that return the same type, you can create multiple constructors in your concrete class, each constructor marked with with @AssistedInject
, in order to match the different parameters types of the factory methods. public interface PaymentFactory { Payment create(Date startDate, Money amount); Payment createWithoutDate(Money amount); } public class RealPayment implements Payment { @AssistedInject public RealPayment( CreditService creditService, AuthService authService, @Assisted Date startDate, @Assisted Money amount) { ... } @AssistedInject public RealPayment( CreditService creditService, AuthService authService, @Assisted Money amount) { ... } }
Read full article from FactoryModuleBuilder (Guice latest API)
No comments:
Post a Comment