Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IoC problem with multi binding

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??
}
like image 987
kospiotr Avatar asked Apr 21 '10 15:04

kospiotr


1 Answers

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();
   }
}
like image 106
ColinD Avatar answered Oct 10 '22 01:10

ColinD