mercredi 27 mars 2019

Android: repository pattern what is the best solution to create an object?

This question is about the OOP(class/interface) design.

I am developing an android library, not an app. The app will use this library. This library is developed by Repository pattern.

One repository and 2 data sources (local, remote).

Because the local data source uses "SharedPreference", it needs Context.

Below is my repository interface and implements.

interface MyRepository {

    fun create(String data)

    fun get(key: String): String
}

class MyRepositoryImpl(
        private val localDataSource: LocalDataSource,
        private val remoteDataSource: RemoteDataSource
): MyRepository {

    fun create(String data) {
        localDataSource.create(data);
        remoteDataSource.create(data);
    }

    fun get(key: String): String {
        // temp code
        return localDataSource.get(key)
    }

    companion object {

        private var instance: MyRepository? = null

        fun getInstance(context: Context): MyRepository {
            if (instance == null) {
                val localDataSource: LocalDataSource = LocalDataSourceImpl.getInstance(context)
                val remoteDataSource: RemoteDataSource = RemoteDataSourceImpl.getInstance()
                instance = MyRepositoryImpl(localDataSource, remoteDataSource)
            }

            return instance!!
        }

    }
}

The MyRepositoryImpl is implemented by the Singleton pattern. Because it should be used anywhere in the app. So the app developers should be able to get the instance of MyRepository like:

val myRepository = MyRepositoryImpl.getInstance(context)
val data = myRepository.get("key")

But It looks weird... "getInstance(context)". I think this is not a good approach. Is there any more smart design, please?

Aucun commentaire:

Enregistrer un commentaire