2016-12-16 30 views
1

我想什麼做注射的抽象是有一個抽象,並通過抽象的參數。因此,如果有一天比翻新改進更好,我想切換它,這樣做很容易。雖然我不知道它是如何做到的。這裏是什麼,我想要做一個基本概述:我如何使用IOC容器像匕首2

public interface ApiClient{ 
    Object getClient() 
} 

public class RetrofitClient implements ApiClient{ 
    private static Retrofit retrofit = null; 

    @Override 
    public Retrofit getClient(){ 
     if(retrofit == null){ 
      OkHttpClient tokenInterceptor = new OkHttpClient.Builder() 
        .addInterceptor(new NetworkInterceptor()) 
        .build(); 

      retrofit = new Retrofit.Builder() 
        .baseUrl("www.hello.com") 
        .addConverterFactory(GsonConverterFactory.create()) 
        .build(); 
     } 
    } 
} 

然後,我想通過傳遞ApiClient作爲參數來使用它:

public class MyClass{ 
    private ApiClient apiClient; 

    public MyClass(ApiClient apiClient){ 
     this.apiClient = apiClient; 
    } 

    public void getSomeData(){ 
     MyClient client = this.client.create(MyClient.class); 
    } 
} 

我需要注入RetrofitClientMyClass的一些方法。 請建議一個國際奧委會容器的任何其他選擇和我將如何使用它來實現這一點,謝謝。

此鏈接提供更深入的描述於它是使用C#和城堡溫莎https://github.com/castleproject/Windsor/blob/master/docs/basic-tutorial.md

回答

0

在Java完成,如在C#,抽象通過接口或抽象類來表示。

你所提議可能被稱爲「在界面包裝的外部庫,以允許配置交換」。要做到這一點,您必須檢查您希望能夠換出的結核所暴露的方法,並創建一個與之匹配的新界面。

例如,如果外部庫中有這樣的方法:

public class ExternalLibrary { 
    void foo() { 
     //foo implementation 
    } 

    void bar() { 
     //bar implementation 
    } 
} 

您可以創建一個包裝接口:

public interface FooBarable { 
    void foo(); 
    void bar(); 
} 

下一步是使ExternalLibrary消費者在你的應用程序取決於FooBarable

public class MyActivity extends Activity { 

    FooBar fooBar; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     DaggerFooBarComponent 
      .builder() 
      .fooBarModule(new ExternalLibraryModule()) 
      .build() 
      .inject(this); 
    } 
} 

如果您ED交換ExternalLibrary,比如說,測試模擬,你可以在Dagger 2 User Guide使用測試組件按照說明書來進行測試:

public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     DaggerTestFooBarComponent 
      .builder() 
      .mockFooBarModule(new MockFooBarableModule()) 
      .build() 
      .inject(this); 
    } 

怎麼看DI框架/ IOC容器匕首2期工程所有的這個,你必須看user guideGoogle Dagger 2 Android app blueprint,因爲在一個答案的範圍內有太多的解釋。