Roboguice 中最常用的一種綁定為 Linked Bindings,將某個類型映射到其實現(xiàn)。這里我們使用引路蜂二維圖形庫中的類為例,引路蜂二維圖形庫的使用可以參見 Android簡明開發(fā)教程八:引路蜂二維圖形繪制實例功能定義
使用下面幾個類 IShape, Rectangle, MyRectangle, MySquare, 其繼承關(guān)系如下圖所示:
http://wiki.jikexueyuan.com/project/android-roboguice/images/4.png" alt="" />
下面代碼將 IShape 映射到 MyRectangle
public class Graphics2DModule extends AbstractAndroidModule{
@Override
protected void configure() {
bind(IShape.class).to(MyRectangle.class);
}
}
此時,如果使用 injector.getInstance(IShape.class) 或是 injector 碰到依賴于 IShape 地方時,它將使用 MyRectangle。可以將類型映射到它任意子類或是實現(xiàn)了該類型接口的所有類。也可以將一個實類(非接口)映射到其子類,如
bind(MyRectangle.class).to(MySquare.class);
下面例子使用 @Inject 應(yīng)用 IShape.
public class LinkedBindingsDemo extends Graphics2DActivity{
@Inject IShape shape;
protected void drawImage(){
/**
* The semi-opaque blue color in
* the ARGB space (alpha is 0x78)
*/
Color blueColor = new Color(0x780000ff,true);
/**
* The semi-opaque yellow color in the
* ARGB space ( alpha is 0x78)
*/
Color yellowColor = new Color(0x78ffff00,true);
/**
* The dash array
*/
int dashArray[] = { 20 ,8 };
graphics2D.clear(Color.WHITE);
graphics2D.Reset();
Pen pen=new Pen(yellowColor,10,Pen.CAP_BUTT,
Pen.JOIN_MITER,dashArray,0);
SolidBrush brush=new SolidBrush(blueColor);
graphics2D.setPenAndBrush(pen,brush);
graphics2D.fill(null,shape);
graphics2D.draw(null,shape);
}
}
使用 bind(IShape.class).to(MyRectangle.class),為了簡化問題,這里定義了 MyRectangle 和 MySquare 都帶有一個不帶參數(shù)的構(gòu)造函數(shù),注入具有帶參數(shù)的構(gòu)造函數(shù)類用法在后面有介紹。
public class MyRectangle extends Rectangle{
public MyRectangle(){
super(50,50,100,120);
}
public MyRectangle(int width, int height){
super(50,50,width,height);
}
}
...
public class MySquare extends MyRectangle {
public MySquare(){
super(100,100);
}
public MySquare(int width){
super(width,width);
}
}
http://wiki.jikexueyuan.com/project/android-roboguice/images/6.png" alt="" />
Linked bindings 允許鏈接,例如
public class Graphics2DModule extends AbstractAndroidModule{
@Override
protected void configure() {
bind(IShape.class).to(MyRectangle.class);
bind(MyRectangle.class).to(MySquare.class);
}
}
此時當(dāng)需要 IShape 時,Injector 返回 MySquare 的實例, IShape->MyRectangle->MySquare
http://wiki.jikexueyuan.com/project/android-roboguice/images/7.png" alt="" />