引用规则
源码依赖只能指向内
这取决于我猜的架构。让我用一个例子来解释一下:
架构:
DOMAIN <- DATA <- PRESENTATION
地点:
DATA -> LOCAL
|
v
REMOTE
注意: DOMAIN 代表最内圈,PRESENTATION 代表最外圈。
现在 DOMAIN 是一个纯 Kotlin 模块,没有任何 Android 依赖项。让我们定义一个存储库:
interface ProfileRespository {
fun getProfile(): Profile?
fun updateProfile(profile: Profile)
}
我们在 DATA 层(这是一个 Android 库)中实现这一点:
class ProfileRepositoryImpl(
private val networkManager: NetworkManager,
private val remoteDataSource: ProfileRemoteDataSource,
private val localDataSource: ProfileLocalDataSource
): ProfileRepository {
override fun getProfile(): Profile? {
if(networkManager.isNetworkAvailable) {
localDataSource.insert(remoteDataSource.get())
}
return localDataSource.get()
}
override fun updateProfile(profile: Profile) {
remoteDataSource.update(profile)
}
}
class ProfileRemoteDataSource(
private val api: ProfileApi,
private val mapper: Mapper<ProfileDto, Profile>
) {
fun get(): Profile {
return mapper.toModel(api.getProfile())
}
fun update(profile: Profile) {
api.updateProfile(
mapper.fromModel(profile)
)
}
}
class ProfileLocalDataSource(
private val dao: ProfileDao
private val mapper: Mapper<ProfileEntity, Profile>
) {
fun insert(profile: Profile) {
return dao.update(mapper.fromModel(profile))
}
fun get(): Profile? {
return dao.getProfile()?.let(mapper::toModel)
}
}
interface Mapper<T : Any, R : Any> {
fun toModel(value: T): R
fun fromModel(value: R): T
}
LOCAL 模块是一个独立于任何依赖项的 Android 库,并公开了 DAO 和 Entity 对象:
interface ProfileDao {
fun insert(profile: ProfileEntity)
fun get(): ProfileEntity?
}
同样,对于REMOTE 模块:
interface ProfileApi {
fun get(): ProfileDto
fun update(profile: ProfileDto)
}
所以,让Source 类返回DTO 和Entity 对象对我来说没有意义。 repo 类看起来像这样:
class ProfileRepositoryImpl(
private val networkManager: NetworkManager,
private val remoteDataSource: ProfileRemoteDataSource,
private val remoteDataMapper: Mapper<ProfileEntity, Profile>,
private val localDataSource: ProfileLocalDataSource,
private val localDataMapper: Mapper<ProfileDto, Profile>
): ProfileRepository {
override fun getProfile(): Profile? {
if(networkManager.isNetworkAvailable) {
val profile = remoteDataMapper.ToModel(remoteDataSource.get())
localDataSource.insert(localDataMapper.fromModel(profile))
}
return localDataMapper.toModel(localSource.get())
}
override fun updateProfile(profile: Profile) {
remoteDataSource.update(remoteDataMapper.fromModel(profile))
}
}
在您的示例中,您只考虑了GET 操作。在这里,对于UPDATE 操作,我们还需要映射 DOMAIN 对象。因此,当我们添加更多功能时,如果对象的映射是在 Repo 类中完成的,那么 Repo 类会变得非常混乱。
我相信这将取决于系统的整体架构。