MVVM最佳实践是将一个存储库用于多个Dao吗?

时间:2019-05-22 17:06:24

标签: java android mvvm kotlin repository-pattern

我正在尝试使用MVVM设计模式构建Android应用。我目前使用Realm作为数据库,为3种不同类型的PostType创建了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 
             }
        }
    }
}

那么我应该为我的每种帖子类型创建1个存储库,还是为所有3种帖子类型创建1个存储库,因为它们具有一些共同的属性?

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

任何与此文档相关的链接都将受到赞赏。

1 个答案:

答案 0 :(得分:0)

两个daos一个存储库的示例

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();
}