Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
Kotlin Singletons: objeto frente a una clase con constructor privado

La aplicación de ejemplo de girasol de Google utiliza una clase privada con un objeto complementario para implementar un patrón Singleton de su repositorio en lugar de simplemente implementar el repositorio como un objeto (inherentemente Singleton).

Esta es la primera vez que veo un Singleton implementado de esta manera en Kotlin en lugar de implementarlo como un Objeto. ¿En qué contexto(s) debería usarse esta implementación de constructor privado en lugar de la implementación de Objeto más común?

 class GardenPlantingRepository private constructor( private val gardenPlantingDao: GardenPlantingDao ) { suspend fun createGardenPlanting(plantId: String) { withContext(IO) { val gardenPlanting = GardenPlanting(plantId) gardenPlantingDao.insertGardenPlanting(gardenPlanting) } } suspend fun removeGardenPlanting(gardenPlanting: GardenPlanting) { withContext(IO) { gardenPlantingDao.deleteGardenPlanting(gardenPlanting) } } fun getGardenPlantingForPlant(plantId: String) = gardenPlantingDao.getGardenPlantingForPlant(plantId) fun getGardenPlantings() = gardenPlantingDao.getGardenPlantings() fun getPlantAndGardenPlantings() = gardenPlantingDao.getPlantAndGardenPlantings() companion object { // For Singleton instantiation @Volatile private var instance: GardenPlantingRepository? = null fun getInstance(gardenPlantingDao: GardenPlantingDao) = instance ?: synchronized(this) { instance ?: GardenPlantingRepository(gardenPlantingDao).also { instance = it } } } }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

El uso de un object es un problema si su instancia de singleton necesita parámetros, como en este caso aquí, con GardenPlantingDao , ya que no pueden tomar argumentos de constructor. Esto surge con frecuencia en Android, ya que hay muchos casos en los que singletons requiere un Context para funcionar.

Todavía podría usar un object en estos casos, pero sería inseguro o inconveniente:

  • La primera opción sería proporcionarle sus dependencias usando un método setter antes de usar cualquiera de sus otros métodos. Esto significaría que todos los demás métodos tendrían que verificar si las dependencias se han inicializado y, probablemente, arrojar excepciones en caso de que no lo hayan hecho, lo que genera problemas de tiempo de ejecución.
  • Alternativamente, podría requerir dependencias como argumentos para cada método del singleton, lo cual es tedioso en el sitio de la llamada.

De ahí la forma "tradicional" de implementar un singleton con un constructor privado y un método de fábrica.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!