Dagger基础-@Subcomponent和@Name

需要用到的相关的类
对象类:HttpObject,DatabaseObject
Module类:HttpModule,DatabaseModule
Component(组件):DatabaseComponent,HttpComponent

HttpObject.java

public class HttpObject {
    public String baseUrl;

    public HttpObject(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public HttpObject() {

    }
}

DatabaseObject.java

public class DatabaseObject {
}

HttpModule.java

@Module
public class HttpModule {
    ArrayList baseUrl;

    public HttpModule(ArrayList baseUrl){
        this.baseUrl = baseUrl;
    }

    @Named("base1")
    @Provides
    public HttpObject provideHttpObject1(){
        return new HttpObject(baseUrl.get(0));
    }

    @Named("base2")
    @Provides
    public HttpObject provideHttpObject2(){
        return new HttpObject(baseUrl.get(1));
    }
>上面提供了两个方法来返回HttpObject对象,可以动态的根据传入的参数来判断执行HttpObject的哪个构造方法。

//    @Provides
//    public HttpObject provideHttpObject(){
//        return new HttpObject();
//    }
}

DatabaseModule.java

@Module
public class DatabaseModule {

    @Provides
    public DatabaseObject provideDatabaseObject(){
        return new DatabaseObject();
    }
}

HttpComponent.java

@Component(modules = HttpModule.class)
public interface HttpComponent {
    DatabaseComponent buildDatabaseComponent();
}

注意:上面没有提供方法返回对象,直接给到了一个未实现的方法。
DatabaseComponent.java

@Subcomponent(modules = {DatabaseModule.class})
public interface DatabaseComponent {
    void injectMainActivity(MainActivity mainActivity);
}

@Subcomponentd代表一个子组件代表是一个子组件。
使用:
MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Inject @Named("base1")
    HttpObject httpObject1;
    @Inject @Named("base2")
    HttpObject httpObject2;
    @Inject
    DatabaseObject databaseObject;

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

        String url1="www.sina.com.cn";
        String url2="www.163.com.cn";

        ArrayList url=new ArrayList<>();
        url.add(url1);
        url.add(url2);

//        DaggerHttpComponent.builder().httpModule(new HttpModule())
//                .build()
//                .buildDatabaseComponent()
//                .injectMainActivity(this);
//        Log.i("log",httpObject1.hashCode()+"");
//        Log.i("log",httpObject2.hashCode()+"");
//        Log.i("log",databaseObject.hashCode()+"");

        DaggerHttpComponent.builder().httpModule(new HttpModule(url))
                .build()
                .buildDatabaseComponent()//注意这里,子组件这样来写
                .injectMainActivity(this);
        //下面根据url的值来执行HttpObject不同的构造方法。
        Log.i("log",httpObject1.baseUrl+"");// www.sina.com.cn
        Log.i("log",httpObject2.baseUrl+"");// www.163.com.cn
        Log.i("log",databaseObject.hashCode()+"");
    }
}

不建议使用父类和子类那种,建议使用dependens那种依赖,因为前者的子类不能再修改传递参数。

你可能感兴趣的:(Dagger基础-@Subcomponent和@Name)