|
|||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Objectcom.google.inject.assistedinject.FactoryProvider<F,R>
F
- The factory interfaceR
- The concrete class to be created.public class FactoryProvider<F,R>
Provides a mechanism to combine user-specified paramters with
Injector
-specified paramters when creating new objects.
To use a FactoryProvider
:
Annotate your implementation class' constructor with the
@AssistedInject
and the user-specified parameters with
@Assisted
:
public class RealPayment implements Payment {
@AssistedInject
public RealPayment(CreditService creditService, AuthService authService,
@Assisted Date startDate, @Assisted Money amount) {
...
}
}
Write an interface with a create method that accepts the user-specified parameters in the same order as they appear in the implementation class' constructor:
public interface PaymentFactory {
Payment create(Date startDate, Money amount);
}
You can name your create methods whatever you like, such as create,
or createPayment or newPayment. The concrete class must
be assignable to the return type of your create method. You can also provide
multiple factory methods, but there must be exactly one
@AssistedInject
constructor on the implementation class for each.
In your Guice module
, bind your factory
interface to an instance of FactoryProvider
that was created with
the same factory interface and implementation type:
bind(PaymentFactory.class).toProvider(
FactoryProvider.newFactory(PaymentFactory.class, RealPayment.class));
Now you can @Inject
your factory interface into your
Guice-injected classes. When you invoke the create method on that factory, the
FactoryProvider
will instantiate the implementation class using
parameters from the injector and the factory method.
public class PaymentAction {
@Inject private PaymentFactory paymentFactory;
public void doPayment(Money amount) {
Payment payment = paymentFactory.create(new Date(), amount);
payment.apply();
}
}
Method Summary | ||
---|---|---|
F |
get()
Provides an instance of T . |
|
static
|
newFactory(Class<X> factoryType,
Class<Y> implementationType)
|
Methods inherited from class java.lang.Object |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Method Detail |
---|
public static <X,Y> FactoryProvider<X,Y> newFactory(Class<X> factoryType, Class<Y> implementationType)
public F get()
Provider
T
. Must never return null
.
get
in interface Provider<F>
|
|||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |