【问题标题】:Is it best practice MVVM to use one repository for multiple Dao?将一个存储库用于多个 Dao 是最佳实践 MVVM 吗?
【发布时间】:2019-10-09 05:43:02
【问题描述】:

我正在尝试使用 MVVM 设计模式构建一个 Android 应用程序。我目前使用 Realm 作为数据库,为 3 种不同类型的 PostTypes 创建了 3 种类型的 Dao(Dao1、Dao2、Dao3)。我的 3 Daos 看起来很相似,但包含具有一些相同变量的 Object,但也包含许多不同的变量。

class Dao1(db: Realm) : Dao<PostType1>(db) {

    fun findAllAsync(): LiveData<RealmResults< PostType1 >> {
        return RealmResultsLiveData(where().findAllAsync())
    }

    fun findById(id: Int): LiveData< PostType1 >? {
        return RealmLiveData(where().equalTo("id", id).findFirst())
    }

    private fun where(): RealmQuery<CTDCastaway> {
        return db.where(PostType1::class.java)
    }
}

我正在尝试确定是否应该为每个 Dao 或 1 创建一个存储库来统治它们。

class PostRepositary private constructor(val postsDao1: Dao1?){
    fun getDao1Posts() = postsDao1?.findAllAsync()
    fun getDao1PostById(entityId: Int) = postsDao1?.getById(entityId)

    companion object{
        @Volatile private var instance:PostRepositary? = null
        fun getWildlifeInstance(postsDao1: Dao1) =
            instance ?: synchronized(this){
                instance ?: PostRepositary(postsDao1).also { 
                instance = it 
             }
        }
    }
}

那么考虑到它们共享一些共同的属性,我应该为我的每种 Post 类型创建 1 个存储库还是为所有 3 个 Post 类型创建 1 个存储库?

我将如何为多个 Daos 创建单个存储库?

任何与此相关的文档链接将不胜感激。

【问题讨论】:

  • 我有 2 个存储库和 2 个 daos 一个用于我的用户,一个用于我的卡(我的应用程序的主要对象)我不知道为什么我这样做,但我认为它比一个更干净的解决方案要统治所有这些,您在设置方面需要什么帮助?
  • 我想我可能会这样做,我最终会得到很多对象,并且喜欢使用一个存储库来管理许多类似对象的想法。
  • 您可以将它们归为一类,因为它们都需要相同的 DbHelper 来实例化它们,但我不需要
  • 我尝试过这样做,但不幸的是我失败了......这已经超出了我的能力范围,我想我必须继续练习并阅读更多文档/教程
  • 你尝试了什么?一对一还是两者合二为一?

标签: java android mvvm kotlin repository-pattern


【解决方案1】:

二道一库示例

public class CardRepositoryDummy {

private final CardDao cardDao;
private final UserDao userDao;
private LiveData<List<Card>> cardListLiveData;
private DbHelper db;
private int keystage;
private static final String TAG = "CardRepo";

public CardRepositoryDummy(Application application) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(application);
    keystage = sharedPreferences.getInt(Constants.SHARED_PREF_CARD_KEYSTAGE,0);
    db = DatabaseBuilder.getDatabase(application);
    cardDao = db.cardDaoLive();
    userDao = db.userDao();
}

public CardRepositoryDummy(Context application) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(application);
    keystage = sharedPreferences.getInt(Constants.SHARED_PREF_CARD_KEYSTAGE,0);
    db = DatabaseBuilder.getDatabase(application);
    cardDao = db.cardDaoLive();
    userDao = db.userDao();
}

【讨论】:

    猜你喜欢
    • 2015-09-21
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 2011-07-27
    相关资源
    最近更新 更多