上例說過如果需要構(gòu)造一些較復(fù)雜的類的實例,通常的方法是使用 @Provides 方法。這個方法必須定義在模塊中 (Module),而且必須使用 @Provides 標(biāo)注,在個方法的返回類型則綁定到這個方法返回的對象實例。
如果這個方法帶有 binding Annotation 或是 @Named(“xxx”),Guice 則將 @Provides 方法返回的對象綁定到這個 annotated 類型。
例使用 @Provides 創(chuàng)建三個圓,然后再屏幕上顯示出來,圖形庫的使用可以參見 Android簡明開發(fā)教程十二:引路蜂二維圖形庫簡介及顏色示例 . 其實創(chuàng)建圓并不復(fù)雜,這里只是用來說明 @Provides 方法的用法。
在 Graphics2DModule 在添加三個 @Provides 方法:
@Provides @Named("Circle1")
IShape provideCircle1(){
return new Ellipse(30,60,80,80);
}
@Provides @Named("Circle2")
IShape provideCircle2(){
return new Ellipse(60,30,80,80);
}
@Provides @Named("Circle3")
IShape provideCircle3(){
return new Ellipse(90,60,80,80);
}
分別綁定到 IShape 帶有標(biāo)注 @Named(“Circle1″),@Named(“Circle2″),@Named(“Circle3″).
創(chuàng)建 ProvidesMethodsDemo,有如下代碼
public class ProvidesMethodsDemo extends Graphics2DActivity{
@Inject @Named("Circle1") IShape circle1;
@Inject @Named("Circle2") IShape circle2;
@Inject @Named("Circle3") IShape circle3;
protected void drawImage(){
// The solid (full opaque) red color in the ARGB space
Color redColor = new Color(0xffff0000);
// The semi-opaque green color in the ARGB space (alpha is 0x78)
Color greenColor = new Color(0x7800ff00,true);
// 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();
SolidBrush brush=new SolidBrush(redColor);
graphics2D.fill(brush,circle1);
brush=new SolidBrush(greenColor);
graphics2D.fill(brush,circle2);
Pen pen=new Pen(yellowColor,10,Pen.CAP_BUTT,Pen.JOIN_MITER,dashArray,0);
brush=new SolidBrush(blueColor);
graphics2D.setPenAndBrush(pen,brush);
graphics2D.fill(null,circle3);
graphics2D.draw(null,circle3);
}
}
@Provides 方法通常用來創(chuàng)建將復(fù)雜的類對象,可以帶參數(shù),參數(shù)也可以通過注入傳入比如:
@Provides @Named("Circle1")
IShape provideCircle1(@Named("width") int width){
return new Ellipse(30,60,width,width);
}
http://wiki.jikexueyuan.com/project/android-roboguice/images/11.png" alt="" />