Oh, Jesse also has AssistedInject which can help with this stuff, but I
still like to kick it old school. He can tell you more.
Bob
On Thu, Oct 16, 2008 at 9:16 AM, Bob Lee <[EMAIL PROTECTED]> wrote:
> Assuming you need to inject stuff into DispatchHandler and you don't want
> Dispatcher to know about DispatchHandler's deps, here's how I would do it.
>
> public class Dispatcher {
>
> private final DispatchHandler.Factory handlerFactory;
>
> // package-private for unit testing
> @Inject Dispatcher(DispatchHandler.Factory handlerFactory) {
> this.handlerFactory = handlerFactory;
> }
>
> ...
>
> public boolean dispatch() {
> for(PredictorProfile predictor : predictors) {
> handlerFactory.newInstance(predictor).start();
> }
> return true;
> }
> }
>
> public class DispatchHandler extends Thread {
>
> private DispatchHandler(PredictorProfile predictor, Dep1 d1, ...) { ... }
>
> ...
>
> public static class Factory {
>
> private final Dep1 d1;
> ...
>
> // package-private so we can unit test easily.
> @Inject Factory(Dep1 d1, ...) { ... }
>
> ...
>
> public DispatchHandler newInstance(PredictorProfile predictor) {
> return new DispatchHandler(predictor, d1, ...);
> }
> }
> }
>
> You could also use "Builder" instead of "Factory" depending on how you
> structure things. Needing this additional class is unfortunate but necessary
> unless we extend the language to better support this stuff.
>
> Bob
>
>
> On Thu, Oct 16, 2008 at 9:02 AM, Andrew Clegg <[EMAIL PROTECTED]>wrote:
>
>>
>> Hey folks,
>>
>> I'm just getting started with Guice (and DI in general). I have a
>> question, hope it's not too dense.
>>
>> I have a method that looks something like this in its first
>> incarnation (_predictors is a collection):
>>
>> public boolean dispatch()
>> {
>> for( PredictorProfile predictor : _predictors )
>> {
>> Thread handler = new DispatchHandler( predictor );
>> handler.run();
>> }
>> return true;
>> }
>>
>> i.e. for each predictor that the object knows about, kick off a thread
>> to process it, and then return. (The return true is just a placeholder
>> for a proper status code later.)
>>
>> Now I've started to think Guicily, I don't like the look of that call
>> to new. Everything else in this app so far is injected for me by
>> Guice.
>>
>> What's the best pattern for this kind of situation?
>>
>> Thanks!
>>
>> Andrew.
>>
>> >>
>>
>
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"google-guice" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/google-guice?hl=en
-~----------~----~----~----~------~----~------~--~---