Dagger局部单例和全局单例-@Singleton
2019-10-22 本文已影响0人
凌烟醉卧
提供一个HttpObject对象
public class HttpObject {
}
提供一个Module
@Singleton
@Module
public class HttpModule{
@Singleton
@Provides
public HttpObject provederHttpObject(){
return new HttpObject();
}
}
单例类的使用需要在
@Module
修饰的类和@Provides
修饰的方法上分别添加@Singleton
。
提供一个Component
@Singleton
@Component(modules = {HttpModule.class,DatabaseModule.class})
public interface MyComponent
void injectMainActivity(MainActivity mainActivity);
void injectSecondActivity(SecondActivity secondActivity);
}
同时在
@Component
修饰的Componet上添加@Singleton
。
从MainActivity跳转到SecondActivity,来观察HttpObject 是否是一个对象。
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Inject
HttpObject httpObject1;
@Inject
HttpObject httpObject2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//第一种注入方法
DaggerMyComponent.create().injectMainActivity(this);
//第二种注入方法
// DaggerMyComponent.builder().httpModule(new HttpModule())
// .build()
// //到这里就已经产生了module和component对象
// .injectMainActivity(this);
Log.i("log",httpObject1.hashCode()+"");//189244270
Log.i("log",httpObject2.hashCode()+"");//189244270
Log.i("log",databaseObject.hashCode()+"");//69880476
}
public void jump(View view) {
this.startActivity(new Intent(this,SecondActivity.class));
}
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
@Inject
HttpObject httpObject;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaggerMyComponent.create().injectSecondActivity(this);
Log.i("log",httpObject.hashCode()+"");//115744208
}
}
可以看到,在MainActivity中HttpObject的HashCode是一样的,说明是一个对象;而在SecondActivity中HttpObject的HashCode发生了变化,和MainActivity是不一样的,这就是局部单例。
下面来把局部单例变为全局单例。
其它的类都不需要修改,只需要在Application中操作即可。
MyApplication.java
public class MyApplication extends Application {
private MyComponent myComponent;
@Override
public void onCreate() {
super.onCreate();
myComponent= DaggerMyComponent.builder()
.httpModule(new HttpModule())
// .presenterComponent(DaggerPresenterComponent.builder()
// .presenterModule(new PresenterModule())
.build();
}
public MyComponent getAppComponent(){
return myComponent;
}
}
在Activitie中使用的如下:
((MyApplication)getApplication()).getAppComponent().injectMainActivity(this);