This is a classic case for using a Mapbinder:
http://code.google.com/p/google-guice/wiki/Multibindings
The two key aspects:
public void FetcherModule extends AbstractModule {
@Override
protected void configure() {
Mapbinder<FetchType, IFetcher> mapbinder =
MapBinder.newMapBinder(binder(), FetchType.class, IFetcher.class);
mapbinder.addBinding(FetchType.STREAM, StreamFetcher.class);
mapbinder.addBinding(FetchType.MEMOBERY, MemoryFetcher.class);
....
}
}
And then:
class InvokeFetcher {
private final Map<FetchType, IFetcher> fetchersByType;
@Inject
InvokeFetcher(Map<FetchType, IFetcher> fetchersByType) {
this.fetchersByType = fetchersByType;
}
void fetch(FetchRecord fetchRecord) {
IFetcher fetcher = com.google.base.Preconditions.checkNonNull(
fetchersByType.get(fetchRecord.getType),
"No fetcher found for type [%s] within [%s]",
fetchRecord.getType(), fetchersByType));
fetcher.fetch();
}
}
-Fred
On Sun, Jun 6, 2010 at 3:09 AM, xp <[email protected]> wrote:
> Hi,
>
> I am new to guice and trying to explore on how to use it in my
> project. I have the following use case:
>
> 1) interface IFetcher { void fetch(); }
>
> 2) Multiple implementation:
> class StreamFetcher implements IFetcher { void fetch(){} }
> class MemoryFetcher implements IFetcher { void fetch(){} }
> class DBFetcher implements IFetcher { void fetch(){} }
> ..... There are around 6-7 types.
>
> 3) class FetchRecord {
> private FetchType fetchType;
> // ... data
> public getType(){
> return fetchType;
> }
> }
>
>
> 4) Have a fetcherCaller
> class InvokeFetcher {
> private EnumMap<FetchType, IFetcher> fetcherMap;
> public fetch(FetchRecord record) {
> fetcherMap.get(record.getType).fetch();
> }
> }
>
> Currently I have modeled this using spring ioc. Could anyone guide me
> on how to achieve this using guice?
>
> Thanks in advance!
>
>
>
>
> --
> 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]<google-guice%[email protected]>
> .
> For more options, visit this group at
> http://groups.google.com/group/google-guice?hl=en.
>
>
--
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.