Android RoboGuice 使用指南(4):Linked Bindings

jerry Android 2015年08月24日 收藏

Roboguice 中最常用的一种绑定为Linked Bindings,将某个类型映射到其实现。这里我们使用引路蜂二维图形库中的类为例,引路蜂二维图形库的使用可以参见Android简明开发教程八:引路蜂二维图形绘制实例功能定义。

使用下面几个类 IShape, Rectangle, MyRectangle, MySquare, 其继承关系如下图所示:

下面代码将IShape 映射到MyRectangle

  1. public class Graphics2DModule extends AbstractAndroidModule{
  2.  
  3. @Override
  4. protected void configure() {
  5.  
  6. bind(IShape.class).to(MyRectangle.class);
  7.  
  8. }
  9. }

此时,如果使用injector.getInstance(IShape.class) 或是injector 碰到依赖于IShape地方时,它将使用MyRectangle。可以将类型映射到它任意子类或是实现了该类型接口的所有类。也可以将一个实类(非接口)映射到其子类,如

bind(MyRectangle.class).to(MySquare.class);

下面例子使用@Inject 应用IShape.

  1. public class LinkedBindingsDemo extends Graphics2DActivity{
  2.  
  3. @Inject IShape  shape;
  4.  
  5. protected void drawImage(){
  6.  
  7. /**
  8. * The semi-opaque blue color in
  9. * the ARGB space (alpha is 0x78)
  10. */
  11. Color blueColor = new Color(0x780000ff,true);
  12. /**
  13. * The semi-opaque yellow color in the
  14. * ARGB space ( alpha is 0x78)
  15. */
  16. Color yellowColor = new Color(0x78ffff00,true);
  17.  
  18. /**
  19. * The dash array
  20. */
  21. int dashArray[] = { 20 ,8 };
  22. graphics2D.clear(Color.WHITE);
  23. graphics2D.Reset();
  24. Pen pen=new Pen(yellowColor,10,Pen.CAP_BUTT,
  25. Pen.JOIN_MITER,dashArray,0);
  26. SolidBrush brush=new SolidBrush(blueColor);
  27. graphics2D.setPenAndBrush(pen,brush);
  28. graphics2D.fill(null,shape);
  29. graphics2D.draw(null,shape);
  30.  
  31. }
  32.  
  33. }

使用bind(IShape.class).to(MyRectangle.class),为了简化问题,这里定义了MyRectangle和MySquare都带有一个不带参数的构造函数,注入具有带参数的构造函数类用法在后面有介绍。

  1. public class MyRectangle extends Rectangle{
  2. public MyRectangle(){
  3. super(50,50,100,120);
  4. }
  5.  
  6. public MyRectangle(int width, int height){
  7. super(50,50,width,height);
  8. }
  9. }
  10. ...
  11. public class MySquare extends MyRectangle {
  12.  
  13. public MySquare(){
  14. super(100,100);
  15. }
  16.  
  17. public MySquare(int width){
  18. super(width,width);
  19. }
  20.  
  21. }

Linked bindings 允许链接,例如

  1. public class Graphics2DModule extends AbstractAndroidModule{
  2.  
  3. @Override
  4. protected void configure() {
  5. bind(IShape.class).to(MyRectangle.class);
  6. bind(MyRectangle.class).to(MySquare.class);
  7.  
  8. }
  9. }

此时当需要IShape 时,Injector返回MySquare 的实例, IShape->MyRectangle->MySquare