Skip to content

模块化架构 (Modularization)

在多模块(Multi-module)项目中,最棘手的问题是:Feature A 需要跳转到 Feature B,但 Feature A 不能依赖 Feature B(否则循环依赖)。

1. 导航解耦

我们不应该直接引用目标页面的 Composable 函数,而是通过路由接口深层链接

方案 A: 路由表下沉 (推荐)

创建一个 :core:navigation 模块,所有 Feature 模块都依赖它。

kotlin
// :core:navigation
sealed class Screen(val route: String) {
    object Home : Screen("home")
    object Detail : Screen("detail/{id}") {
        fun createRoute(id: String) = "detail/$id"
    }
}

Feature A 跳转 Feature B 时:

kotlin
navController.navigate(Screen.Detail.createRoute("123"))

方案 B: 依赖注入 (DI) 路由

定义一个 NavigationProvider 接口。

kotlin
interface DetailNavigation {
    fun navigateToDetail(id: String)
}

// Feature B 实现它
class DetailNavigationImpl @Inject constructor(val navController: NavController) : DetailNavigation { ... }

// Feature A 注入它
@Inject lateinit var detailNav: DetailNavigation

2. API 模块与 IMPL 模块

对于公共组件(如 UserCard),如果 Feature A 和 B 都要用,应该将其提取到 :feature:user:api 模块(只包含接口和数据类)或 :core:ui 模块。

3. 依赖图

理想的架构图:

mermaid
graph TD
    App --> FeatureA
    App --> FeatureB
    FeatureA --> CoreUI
    FeatureB --> CoreUI
    FeatureA --> CoreNav
    FeatureB --> CoreNav
    CoreUI --> CoreDesignSystem