Dagger2理解模版

直接从实例化传参数开始:

@Module
public class MainModule {   //容器

    private Context mContext;

    public MainModule(Context context){
        mContext = context;
    }

    @Provides
    Context providesContext(){
        // 提供上下文对象
        return mContext;

    }

    @Provides // 关键字,标明该方法提供依赖对象
    @Singleton                              //单例模式注解
    People providerPeople(Context context){

        return new People(context);

    }

}
@Singleton                              //单例模式注解
@Component(modules = MainModule.class)
public interface MainComponent {          //桥梁

    void inject(MainActivity activity);

}
public class People {   //需要实例化的类

    private Context context;
    public People(Context context) {
        this.context = context;
        Log.e("People","People类创建");
    }
    
}
public class MainActivity extends AppCompatActivity {

    @Inject
    People people1;   //这里用两个参数是测试对象的单例,是否是同一个对象

    @Inject
    People people2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MainComponent build = DaggerMainComponent.builder().mainModule(new MainModule(this)).build();

        build.inject(this);

        Log.e("MaiNActivity","people1:"+people1.toString()+"------"+"people2:"+people2.toString());   //打印两个对象的地址,用上单例了,两个对象为同一个对象

    }
}
01-15 02:11:40.114 2724-2724/com.bwie.dongchangqi.testmodule E/MaiNActivity: people1:com.bwie.dongchangqi.testmodule.People@4a828840------people2:com.bwie.dongchangqi.testmodule.People@4a828840    //打印结果,两个对象的地址一样,用上了单例模式




你可能感兴趣的:(Dagger2理解模版)