Implementation of Android Simple Service Locator Pattern
- 2021-12-11 19:10:01
- OfStack
Dependency injection (Dependency Injection) and service locator (Service Locator) are two main means to implement inversion of control (Inversion of Control).
The mainstream dependency injection frameworks of Android are: Dagger and Kion
These dependency injection frameworks all feel heavy.
For example, service locators are rare, and a simple service locator pattern implementation is provided here.
Introduce
Project address: github. com/czy1121/ser …
repositories {
maven { url "https://gitee.com/ezy/repo/raw/android_public/"}
}
dependencies {
implementation "me.reezy.jetpack:servicelocator:0.4.0"
}
API
// Get an instance
inline fun <reified T> resolve(name: String = T::class.java.name): T?
// Register as Singleton
inline fun <reified T> singleton(name: String = T::class.java.name, crossinline block: () -> T)
// Register as a factory
inline fun <reified T> factory(name: String = T::class.java.name, crossinline block: () -> T)
Use
Singleton, each resolve gets the same instance
class SomeService {
fun doSomething() {
}
}
// Registration
singleton {
SomeService()
}
// Get
val service = resolve<SomeService>()
List examples
class NamedService(val name: String) {
fun doSomething() {
}
}
// Registration
singleton("a") {
NamedService("aaa")
}
singleton("b") {
NamedService("bbb")
}
// Get
val serviceA = resolve<NamedService>("a")
val serviceB = resolve<NamedService>("b")
Factory, each resolve will generate a new instance
class SomeService {
fun doSomething() {
}
}
// Registration
factory {
SomeService()
}
// Get, every time resolve A new instance will be generated
val service1 = resolve<SomeService>()
val service2 = resolve<SomeService>()
Named factory
class NamedService(val name: String) {
fun doSomething() {
}
}
// Registration
factory("a") {
NamedService("aaa")
}
factory("b") {
NamedService("bbb")
}
// Get
// A1 And A2 Is to use the same 1 Different instances produced by factories
// A1 And B1 Is to use different instances generated by different factories
val serviceA1 = resolve<NamedService>("a")
val serviceA2 = resolve<NamedService>("a")
val serviceB1 = resolve<NamedService>("b")
val serviceB2 = resolve<NamedService>("b")
The above is the Android Simple Service Locator Mode implementation details, more information about the Android Simple Service Locator Mode please pay attention to other related articles on this site!