我目前正在将我的项目架构从 MVP 转换为 MVVM。当我研究它时,我发现有些事情让我感到困惑:
在ioschedScheduleViewModelFactory.kt
项目中,工厂实现了ViewModelProvider.Factory:
class ScheduleViewModelFactory(
private val userEventRepository:DefaultSessionAndUserEventRepository
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(ScheduleViewModel::class.java)) {
return ScheduleViewModel(LoadUserSessionsByDayUseCase(userEventRepository)) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
在DetailViewModelFactory.java
来自codelab的 Sunshine 项目中,工厂扩展了ViewModelProvider.NewInstanceFactory:
public class DetailViewModelFactory extends ViewModelProvider.NewInstanceFactory {
private final SunshineRepository mRepository;
private final Date mDate;
public DetailViewModelFactory(SunshineRepository repository, Date date) {
this.mRepository = repository;
this.mDate = date;
}
@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
//noinspection unchecked
return (T) new DetailActivityViewModel(mRepository, mDate);
}
}
我想知道:
- ViewModelProvider.Factory和ViewModelProvider.NewInstanceFactory有什么区别?
- 为什么它们像上面提到的代码一样被使用?
- 使用它们的最佳实践/场景是什么?