public class MyClass{ private AnotherClass mAnotherObject; public MyClass(){ mAnotherObject = new AnotherClass(); } }
public class MyClass{ private MyInterface mAnotherObject; public MyClass(MyInterface anotherObject){ mAnotherObject = anotherObject; } }
依賴注入能夠簡化代碼編寫,並提供一個可適配的環境,方便進行單元測試以及功能模塊的配置。 前端
public class FriendListFragment{ private FriendListAPI mFriendListAPI; ...... public FriendListFragment(){ mFriendListAPI = new FriendListAPI(); } private void getFriendList(){ mFriendListAPI.getFriendList(new Callback(){ public void onSuccess(List<User> list){ ...... } ...... }); } } public class FriendListAPI{ private OkHttpClient mHttpClient; public FriendListAPI(){ mHttpClient= new OkHttpClient(); //接下來各類Http配置 ...... } }
代碼寫好了,運行程序試試。但是,後臺API沒有準備好或者沒有數據怎麼辦?本身添點測試數據試試吧。在FriendListFragment裏面添加一個生成測試數據的方方法buildTestData(),並替換getFriendList()方法。等後臺API準備好後再改回來。git
public class FriendListFragment{ private FriendListAPI mFriendListAPI; ...... public FriendListFragment(FriendListAPI friendListAPI){ mFriendListAPI = friendListAPI; } } public class FriendListAPI{ private OkHttpClient mHttpClient; public FriendListAPI(HttpClient okHttpClient){ mHttpClient= okHttpClient; ...... } }
如今引入一個稍微複雜的場景,更多的Fragment須要使用FriendListAPI,咱們須要在兩個不一樣的地方進行注入,所以產生了許多重複代碼。github
public class MyModule{ @Provides @Singleton OkHttpClient provideOkHttpClient(){ //這裏可進行各類Http配置 return new OkHttpClient(); } @Provides @Singleton FriendListAPI provideFriendListAPI(){ return newFriendListAPI(); } }
初始化模塊以及依賴對象圖。服務器
public class MyApplication extends Application{ private ObjectGraph graph; @Override public void onCreate() { super.onCreate(); graph = ObjectGraph.create(getModules().toArray()); } protected List<Object> getModules() { return Arrays.asList( new MyModule(this)); } public void inject(Object object) { graph.inject(object); } }
最後添加註入點並進行注入。網絡
public abstract class BaseActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((MyApplication) getApplication()).inject(this); } } public class FriendListFragment{ @Inject FriendListAPI mFriendListAPI; ...... } public class FriendListAPI{ @Inject OkHttpClient mHttpClient; ...... }
如需進行單元測試,或使用可生成測試數據的模擬API,則再編寫一個模塊,在初始模塊和依賴對象圖時替換便可。框架