call mock myObject in order to write unit tests. public class SomeClass { private final Object myObject; public SomeClass() { myObject = Factory.getObject(); // Hard to replace this } }
asking a factory object to make one for them, you pass the needed dependencies in to the object externally. .. or you can use a dependency injector that builds the dependency graph for you. INJECTING DEPENDENCIES
do stuff: the BarcodeDecoder, the KoopaPhysicsEngine, and the AudioStreamer. These classes have dependencies; perhaps a BarcodeCameraFinder, DefaultPhysicsEngine, and an HttpStreamer. DAGGER 2
ones that take up space without doing much at all: the BarcodeDecoderFactory, the CameraServiceLoader, and the MutableContextWrapper. These classes are the clumsy duct tape that wires the interesting stuff together.
easy to create reusable, interchangeable modules. You can share the same AuthenticationModule across all of your apps. You can run DevLoggingModule during development and ProdLoggingModule in production to get the right behavior in each situation.
the @Inject annotation to indicate that Dagger may create instances as well. class CoffeeMaker { @Inject Heater heater; @Inject Pump pump; @Inject public CoffeeMaker() { } ... }
for semantic clarity • Dagger will inject the same instance inside the scope (local singletons) • If we don’t use scopes then Dagger will create new dependencies every time we inject
graph will use a single instance of the value for all of its clients. @Module public class ApiModule { @Singleton @Provides Services provideServices(@NonNull Retrofit retrofit) { return retrofit.create(Services.class); } ... }
graph will use a single instance of the value for all of its clients. @Module public class ApiModule { @Singleton @Provides Services provideServices(@NonNull Retrofit retrofit) { return retrofit.create(Services.class); } ... }
cause a compiler error if any bindings are invalid or incomplete. @Module class DripCoffeeModule { @Provides Heater provideHeater(Executor executor) { return new CpuHeater(executor); } } [ERROR] error: java.util.concurrent.Executor cannot be provided without an @Provides-annotated method.