views:

112

answers:

1

I'm Java beginner and IoC as well. How to do stuff:


public class Foo{

    //private Bar bar; //Bar is an interface private int var; public Foo(){ } public void setVar(int var){
      this.var = var;
    } public Bar getBar(){
      if(var==1){
        return new BarImpl1(); //an implemantation of Bar interface
      }
      else if(var==2){
        return new BarImpl2(); //an implemantation of Bar interface
      }
      else{
        return new BarImpl(); //an implemantation of Bar interface
      }
    }
}

in IoC way on Guice example?


public class Foo{

    private Bar bar; //Bar is an interface private int var; @Inject public Foo(Bar bar){
      this.bar = bar;
    } public void setVar(int var){
      this.var = var;
    } public Bar getBar(){
      return bar; // or what else??
    }
}

How should I configure my injector?


@Override 
protected void configure() {
    bind(Bar.class).to(BarImpl.class);
    //and what else??
}
+2  A: 

I'm going to assume that var is a code that is determined at runtime based on data, user input, etc. and a single instance of Foo must be able to return different implementations of Bar depending on that code (it's a dynamic Bar factory).

In that case, what you probably want to do is use MapBinder from the Multibinding extension.

You'd probably do something like this:

MapBinder<Integer, Bar> mapbinder
     = MapBinder.newMapBinder(binder(), Integer.class, Bar.class);
mapbinder.addBinding(1).to(BarImpl1.class);
mapbinder.addBinding(2).to(BarImpl2.class);

bind(Bar.class).to(BarImpl.class); // the fallback

Then Foo might look like:

public class Foo {
   private final Provider<Bar> defaultProvider;
   private final Map<Integer, Provider<Bar>> barTypeMap;

   private int var = -1;

   @Inject public Foo(Provider<Bar> defaultProvider, 
                      Map<Integer, Provider<Bar>> barTypeMap) {
     this.defaultProvider = defaultProvider;
     this.barTypeMap = barTypeMap;
   }

   public void setVar(int var) { ... }

   public Bar getBar() {
     if(barTypeMap.containsKey(var)) {
       return barTypeMap.get(var).get();
     }

     return defaultProvider.get();
   }
}
ColinD
Thank you very much. It was exactly how you asssumed. Thanks to you I understood Provider and MapBinder at last :)
kospiotr