Ref
This sample’s idea is from Google Android page (Dependency injection in Android)
From This documentation, the way of dependency injection in Android
- Constructor Injection
- Field Injection (or Setter Injection)
- Automated using library -> Dagger
- Service locator
And, if application becomes bigger, this recommends Automated injection. (over 4 screens)
In this entry, explain Non automated ones first.
Constructor Injection
Constructor injection is a constructor has dependency and when create one class, this class has arguments of other dependent class as constructor.
CPU.kt
class CPU { fun start() {} }
Compuer.kt
class Computer(private val cpu: CPU) { fun start() { cpu.start() } }
MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // 1. Constructor DI val cpu = CPU() val computer = Computer(cpu) computer.start() }
Usage is very simple. Create CPU class first and inject using constructor. If we want to use different CPU, we can create and use. That’s it.
Field type
2nd example is field injection.
Parent has filed of injection target and create class and set using setter
FieldCPU.kt
class FieldCPU { fun start() { } }
FieldComputer.kt
class FieldComputer { lateinit var cpu : FieldCPU fun start() { cpu.start() } }
The key is lateinit. lateinit is inject before using.
MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val fieldcpu = FieldCPU() val fieldComputer = FieldComputer() fieldComputer.cpu = fieldcpu fieldComputer.start() }
Service Locator
3rd example is Service Locator
Create injection component by Locator (kind of Factory). This code is in the target class
LocatorCPU.kt
class LocatorCPU { fun start() {} }
LocatorCPU.kt
class LocatorComputer { private val cpu = ServiceLocator.getCPU() fun start() { cpu.start() } }
ServiceLocator.kt
object ServiceLocator { fun getCPU(): LocatorCPU = LocatorCPU() }
コメント