Android RoboGuice使用指南(6) Instance Bindings

來源:互聯網
上載者:User

我們在前面例子Android RoboGuice 使用指南(4):Linked Bindings 時為簡單 起見,定義MyRectangle和MySquare時為它們定義了一個不帶參數的建構函式,如 MyRectangle的如下:

public class MyRectangle extends Rectangle{      public MyRectangle(){ super(50,50,100,120); } public MyRectangle(int width, int height){ super(50,50,width,height); }}

實際上可以不需要這個不帶參數的建構函式,可以使用Instance Bindings ,Instance Bindings可以將一個類型綁定到一個特定的執行個體對象,通 常用於一個本身不依賴其它類的類型,如各種基本類型,比如:

bind(String.class)      .annotatedWith(Names.named("JDBC URL"))      .toInstance("jdbc:mysql://localhost/pizza");     bind(Integer.class)      .annotatedWith(Names.named("login timeout seconds"))      .toInstance(10);

修改MyRectangle和MySquare的定義如下:

public class MySquare extends MyRectangle {      @Inject  public MySquare(@Named("width") int width){      super(width,width);      }     }     ...     public class MyRectangle extends Rectangle{                @Inject  public MyRectangle(@Named("width") int width,      @Named("height")int height){      super(50,50,width,height);      }     }

去掉了無參數的建構函式,可以將標註為@Named(“width”)的int 類 型綁定到100,添加下面綁定:

bind(Integer.class)      .annotatedWith(Names.named("width"))      .toInstance(100);     bind(Integer.class)      .annotatedWith(Names.named("height"))      .toInstance(120);

運行這個例子,可以得到和前面例子同樣的結果。 此時使用Injector 構造一個MyRectangle 執行個體時,Injector自動選用帶參數的那 個建構函式,使用100,120為width和height注入參數,返回一個MyRectangle對 象到需要引用的地方。

儘管可以使用Instance Bindings將一個類型映射 到一個複雜類型的類執行個體,但RoboGuice不建議將Instance Bindings應用到複雜 類型的執行個體,因為這樣會使應用程式啟動變慢。

正確的方法是使用 @Provides 方法,將在下面介紹。

註:GuiceDemo 中的例子沒用使用列表 的方法來顯示所有樣本,如需運行所需樣本,可以通過Run Configuration-> 設定Launch 的Activity:

查看全套文章:http://www.bianceng.cn/OS/extra/201301/34950.htm

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.