Android 簡單服務(wù)定位器模式實(shí)現(xiàn)
依賴注入(Dependency Injection)和服務(wù)定位器(Service Locator)是實(shí)現(xiàn)控制反轉(zhuǎn)(Inversion of Control)的兩種主要手段。
Android的主流依賴注入框架有:Dagger 和 Kion
這些依賴注入框架都感覺比較重。
服務(wù)定位器比如少見,這里提供一個(gè)一個(gè)簡單的服務(wù)定位器模式實(shí)現(xiàn)。
引入項(xiàng)目地址: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
// 獲取實(shí)例inline fun <reified T> resolve(name: String = T::class.java.name): T?// 注冊為單例inline fun <reified T> singleton(name: String = T::class.java.name, crossinline block: () -> T)// 注冊為工廠inline fun <reified T> factory(name: String = T::class.java.name, crossinline block: () -> T)使用
單例,每次resolve獲得的都是同一實(shí)例
class SomeService { fun doSomething() { }}// 注冊 singleton { SomeService()}// 獲取val service = resolve<SomeService>()
具名單例
class NamedService(val name: String) { fun doSomething() { }}// 注冊 singleton('a') { NamedService('aaa')}singleton('b') { NamedService('bbb')}// 獲取 val serviceA = resolve<NamedService>('a')val serviceB = resolve<NamedService>('b')
工廠,每次resolve都會產(chǎn)生新實(shí)例
class SomeService { fun doSomething() { }}// 注冊 factory { SomeService()}// 獲取,每次resolve都會產(chǎn)生新實(shí)例val service1 = resolve<SomeService>() val service2 = resolve<SomeService>()
具名工廠
class NamedService(val name: String) { fun doSomething() { }}// 注冊 factory('a') { NamedService('aaa')}factory('b') { NamedService('bbb')}// 獲取// A1 與 A2 是使用同一工廠產(chǎn)生的不同實(shí)例// A1 與 B1 是使用不同工廠產(chǎn)生的不同實(shí)例val serviceA1 = resolve<NamedService>('a')val serviceA2 = resolve<NamedService>('a')val serviceB1 = resolve<NamedService>('b')val serviceB2 = resolve<NamedService>('b')
以上就是Android 簡單服務(wù)定位器模式實(shí)現(xiàn)的詳細(xì)內(nèi)容,更多關(guān)于Android 簡單服務(wù)定位器模式的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. PHP驗(yàn)證碼工具-Securimage2. Vue 實(shí)現(xiàn)對quill-editor組件中的工具欄添加title3. JavaScript實(shí)現(xiàn)簡單的彈窗效果4. 我所理解的JavaScript中的this指向5. javascript實(shí)現(xiàn)貪吃蛇小練習(xí)6. PHP利用curl發(fā)送HTTP請求的實(shí)例代碼7. Java commons-httpclient如果實(shí)現(xiàn)get及post請求8. PHP單件模式和命令鏈模式的基礎(chǔ)知識9. 一文帶你徹底理解Java序列化和反序列化10. js實(shí)現(xiàn)碰撞檢測

網(wǎng)公網(wǎng)安備