简体   繁体   中英

Design pattern for creating object graph

I have a situation where I want create a hierarchy of instances (belonging to separate classes) in my android application where each object is standalone ie., they fulfill their own responsibilities. So I dont need any other class to hold references to these objects and call any methods on this class. However I need any entry point ie., these classes should be instantiated when a controller class gets instantiated.

I use dagger to for object instantiation. So if MyClassA and MyClassB are two standalone classes which should get instantiated when MyController gets instantiated, its constructor will look like this

@Inject
public MyController(MyClassA a, MyClassB b) {
  ...
}

But MyController has no reason to hold onto these references. So the code looks confusing as it appears that MyController is unnecessarily injecting these two parameters even if it doesn't use them.

Is there a suggested design pattern in this scenario which avoids this confusion ?

Use builder pattern. Instead of injecting MyClassA and MyClassB, inject a component builder that creates a component (graph) that can create MyClassA and MyClassB. You don't necessarily need to inject these objects but only builder.

@NonNull MyFactory.Builder factory;

@Inject
public MyController(@NonNull MyFactory.Builder factory) {
   this.factory = factory;
}

public void aMethod() {
   // build method can return a new component/graph
   MyClassA  aClass = factory.build().getA(); 
}

Your module looks like

@Module
public MyFactoryModule() {

   @Provides
   MyFactory.Builder provideMyFactory() {
      return DaggerMyFactory.builder();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM