如何通过参数在Kotlin中获取对应单例?优化现有实现
多实例单例模式的优化实现
我需要为某类获取对应单例实例,当前通过如下代码(Code A)实现,调用LessOtherState.getInstance1(context)能始终获取同一个单例instance1,但这种实现方式存在代码冗余、扩展性差的问题,希望优化为通过LessOtherState.getInstances(context, 1)、LessOtherState.getInstances(context, 2)这类带参数的方法获取对应单例。经优化后的Code B可正常运行。
原始实现(Code A)
class LessOtherState private constructor(context: Context) { var openDeleteDialog by mutableStateOf(false) private set fun set_openDeleteDialog(isShow: Boolean) { openDeleteDialog = isShow } companion object { @Volatile private var instance1: LessOtherState? = null @Volatile private var instance2: LessOtherState? = null @Volatile private var instance3: LessOtherState? = null // Singleton fun getInstance1(context: Context): LessOtherState { return instance1 ?: synchronized(this) { instance1 ?: LessOtherState(context).also { instance1 = it } } } // Singleton fun getInstance2(context: Context): LessOtherState { return instance2 ?: synchronized(this) { instance2 ?: LessOtherState(context).also { instance2 = it } } } // Singleton fun getInstance3(context: Context): LessOtherState { return instance3 ?: synchronized(this) { instance3 ?: LessOtherState(context).also { instance3 = it } } } } }
优化后的实现(Code B)
感谢Tenfour04!经优化后的以下代码可正常运行:
companion object { private val instanceMap = ConcurrentHashMap<EDialogbox, EditDialogState>() fun getInstances(context: Context, key: EDialogbox): EditDialogState { return instanceMap.computeIfAbsent(key) { EditDialogState(context) } } }
注:优化方案通过
ConcurrentHashMap存储不同key对应的单例实例,利用computeIfAbsent方法实现线程安全的单例创建,既避免了原始实现中重复的单例代码,又具备良好的扩展性,新增实例只需传入新的key即可。
内容的提问来源于stack exchange,提问作者HelloCW
相关产品推荐
相关产品推荐

