Roboguice 中最常用的一種綁定為Linked Bindings,将某個類型映射到其實作。這裡我們使用引路蜂二維圖形庫中的類為例,引路蜂二維圖形庫的使用可以參見Android簡明開發教程八:引路蜂二維圖形繪制執行個體功能定義。
使用下面幾個類 IShape, Rectangle, MyRectangle, MySquare, 其繼承關系如下圖所示:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5SMwAzMwgDMxEDMy8CX4AzLcFTMwIzLcNHZh9GbwV3LcRnblRnbvNWLwd3LcN3clJHckJ3b39CXt92YuMnYiVGbpJ2btlmL3d3dvw1LcpDc0RHaiojIsJye.png)
下面代碼将IShape 映射到MyRectangle
public class Graphics2DModule extends AbstractAndroidModule{
@Override
protected void configure() {
bind(IShape.class).to(MyRectangle.class);
}
}
此時,如果使用injector.getInstance(IShape.class) 或是injector 碰到依賴于IShape地方時,它将使用MyRectangle。可以将類型映射到它任意子類或是實作了該類型接口的所有類。也可以将一個實類(非接口)映射到其子類,如
bind(MyRectangle.class).to(MySquare.class);
下面例子使用@Inject 應用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都帶有一個不帶參數的構造函數,注入具有帶參數的構造函數類用法在後面有介紹。
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);
}
}
Linked bindings 允許連結,例如
public class Graphics2DModule extends AbstractAndroidModule{
@Override
protected void configure() {
bind(IShape.class).to(MyRectangle.class);
bind(MyRectangle.class).to(MySquare.class);
}
}
此時當需要IShape 時,Injector傳回MySquare 的執行個體, IShape->MyRectangle->MySquare
本例下載下傳