Dagger是為Android和Java平臺提供的在編譯時進行依賴注入的框架,Dagger2解決了基于反射帶來的開發(fā)和性能上的問題。在MVP中Dagger2主要用于做界面和業(yè)務之間的隔離,即V-- Dagger2--P,目的是為了解耦.
Dagger2 GitHub地址:https://github.com/google/dagger
第一步在項目中添加dagger2:
然后同步,添加搞定.
第二步就是簡單使用,本文只是簡單使用@Inject、@Module、@Provides、@Conponent注解,更深入的請參考本文后的鏈接(水平太菜,也講不出來).
1.一般實現View與Presenter之間的交互
簡單的結構目錄.
public class MainActiviityPresenter {
public void setData(){
Toast.makeText(MyApplication.getContext(),"我是Presenter中由Dagger2彈出的吐司",Toast.LENGTH_LONG).show();
}
}
在MainActiviityPresenter 類中只寫了彈出Toast方法.
public class MainActivity extends AppCompatActivity {
MainActiviityPresenter mainActiviityPresenter = new MainActiviityPresenter();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mainActiviityPresenter.setData();
}
});
}
}
創(chuàng)建MainActiviityPresenter 的對象,對象調setData()方法,彈出Toast.
2.Dagger2利用注解實現View與Presenter之間的交互
創(chuàng)建對象new MainActiviityPresenter(),使Activity與Presenter耦合度增強,
Dagger2目的就是為了解耦,所以利用注解來取代new MainActiviityPresenter().
在dagger包的Module包下創(chuàng)建類MainActivityModule
![SBZQC(%VQ4XCW0]3@7LMXX4.png](http://upload-images.jianshu.io/upload_images/3156973-14c197fea4cf1718.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
在dagger包的component包下創(chuàng)建類MainActivityComponent
最后在MainActivity的onCreate的方法中調用
只是一個簡單的使用,寫的簡單的Demo已上傳GitHub,https://github.com/TWBfly/MyDagger2/tree/master
更深入的學習Dagger
http://www.lxweimin.com/p/857a768aec4f
http://frogermcs.github.io/dependency-injection-with-dagger-2-the-api/