Repository和AppContainer

三种文件的关系:
应用层 (InventoryApplication)

容器层 (AppContainer + AppDataContainer)

数据层 (ItemsRepository + OfflineItemsRepository)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
graph TB
subgraph "应用层"
A[InventoryApplication]
end

subgraph "容器层"
B[AppContainer 接口]
C[AppDataContainer 实现]
end

subgraph "数据层"
D[ItemsRepository 接口]
E[OfflineItemsRepository 实现]
end

A --> B
A --> C
C --> D
C --> E

style A fill:#e3f2fd
style B fill:#f3e5f5
style C fill:#e8f5e8
style D fill:#fff3e0
style E fill:#fce4ec

✅ Repository

创建 Repository 的目的:

  1. 简化操作:你不需要知道数据存在哪里(数据库、网络、文件)
  2. 统一接口:不管数据来源是什么,都用同样的方法操作
  3. 便于测试:测试时可以轻松替换成”假数据”

ItemsRepository.kt:

1
2
3
4
5
6
7
8
interface ItemsRepository{
fun getAllItemsStream(): Flow<List<Item>>
fun getItemStream(id: Int): Flow<Item>
suspend fun insertItem(item: Item)
suspend fun deleteItem(item: Item)
suspend fun updateItem(item: Item)

}

OfflineItemsRepository.kt:

1
2
3
4
5
6
7
class OfflineItemsRepository(private val itemDao: ItemDao) : ItemsRepository{
override fun getAllItemsStream(): Flow<List<Item>> = itemDao.getAllItems()
override fun getItemStream(id: Int): Flow<Item> = itemDao.getItem(id)
override suspend fun insertItem(item: Item) = itemDao.insert(item)
override suspend fun deleteItem(item: Item) = itemDao.delete(item)
override suspend fun updateItem(item: Item) = itemDao.update(item)
}

✅依赖项注入 AppContainer

依赖项注入: 在运行时提供依赖项,而不是将其硬编码到调用类中。通俗点说就是在一个类中将所需的对象作为实参传入。

容器: 是一个包含应用所需的依赖项的对象

AppContainer 的目的:

  1. 集中管理:所有需要的”工具”都在一个地方
  2. 自动创建:你不需要手动创建每个工具
  3. 统一配置:所有工具都按照统一的方式配置

AppContainer.kt:

1
2
3
4
5
6
7
8
9
10
interface AppContainer {
val itemsRepository: ItemsRepository
}


class AppDataContainer(private val context: Context) : AppContainer {
override val itemsRepository: ItemsRepository by lazy {
OfflineItemsRepository(InventoryDatabase.getDatabase(context).itemDao())
}
}

✅Application文件

作用:

  1. 创建并管理 AppContainer 实例
  2. 所有需要依赖的类都可以通过这个容器获取
  3. 确保整个应用使用同一个依赖注入容器

InventoryApplication.kt:

1
2
3
4
5
6
7
8
9
10
11
12
class InventoryApplication : Application() {

/**
* AppContainer instance used by the rest of classes to obtain dependencies
*/
lateinit var container: AppContainer

override fun onCreate() {
super.onCreate()
container = AppDataContainer(this)
}
}

在 AndroidManifest.xml 文件的 application 标记内,添加以下代码行。
InventoryApplication 类定义为应用的入口点。此代码用于在启动 MainActivity 之前,初始化 InventoryApplication类中定义的依赖项。

1
2
3
4
<application
android:name=".InventoryApplication"
...
</application>
  • Copyrights © 2023-2025 Hexo

请我喝杯咖啡吧~

支付宝
微信