Moduleの区分化

Google guice2.0 になって Module の記述を区分化するのに PrivateModule が導入された。

class BlueModule extends PrivateModule{
   private int price;
   protected BlueModule(int p){
      this.price = p;
   }
   @Override
   protected void configure(){
      install(new PriceModule(this.price));
      expose(Integer.class).annotatedWith(Names.named("PRICE"));
   }
   @Provides @Named("COLOR") @Exposed
   protected String providedColor(){
      return "Blue";
   }
   @Provides @Named("AUTH") @Exposed
   protected String providedAuth(){
      return "Rachel";
   }
}
==================================
class PriceModule extends PrivateModule{
   private int price;
   protected PriceModule(int p){
      this.price = p;
   }
   @Override
   protected void configure(){
     // ↓このように書くくらいなら、
     // ↓ @Provides @Named @Exposed のメソッドを用意した方がよい!
     //binder().bind(Integer.class)
     //.annotatedWith(Names.named("PRICE"))
     //.toInstance(new Integer(this.price));
     //expose(Integer.class).annotatedWith(Names.named("PRICE"));
   }
   @Provides @Named("PRICE") @Exposed
   protected Integer probidedInteger(){
      return new Integer(this.price);
   }
}
==================================
public final class PaperBuilder{
   private PaperBuilder(){}
   public static Paper create(final PaperType type){
      Injector injector = Guice.createInjector(new AbstractModule(){
         @Override
         protected void configure(){
            bindConstant().annotatedWith(Names.named("SIZE")).to(type.size());
            try{
            install(type.getModuleInstance());
            }catch(Exception e){
               throw new RuntimeException(e);
            }
         }
      });
      return injector.getInstance(PaperInpl.class);
   }
}
==================================
public enum PaperType{
     WHITE (WhiteModule.class , 12 , 1000)
   , BLUE  (BlueModule.class  , 24 , 1200)
   , RED   (RedModule.class   , 32 , 1500);
   //
   private Class<? extends PrivateModule> cls;
   private int price;
   private int size;
   private PaperType(Class<? extends PrivateModule> cls,int size,int price){
      this.cls = cls;
      this.size = size;
      this.price = price;
   }
   public Module getModuleInstance() throws Exception{
      Constructor<? extends PrivateModule> constructor 
      = this.cls.getDeclaredConstructor(new Class<?>[]{int.class});
      return constructor.newInstance(this.price);
   }
   public int size(){
      return this.size;
   }
}
==================================
実行は、
Paper p = PaperBuilder.create(PaperType.BLUE);

System.out.println("color   = "+p.getColor());
System.out.println("size    = "+p.size());
System.out.println("author  = "+p.getAuthor());
System.out.println("price   = "+p.price());
==================================
動的なバインドが整理できるかも。。。