我认为代码A和代码B是等价的,它们将使用以下代码返回Singleton.
preferenceParState: PreferenceParameterState = rememberPreferenceParameterState()
我用preferenceParState.hashCode()
测试它们,我发现代码B可以返回Singleton,但代码A不能返回Singleton,为什么?
顺便说一句,通过我的测试,mContext.hashCode()
在代码A中的不同实例中具有相同的值.
Code A个
class PreferenceParameterState private constructor(context: Context) {
companion object {
@Volatile private var instance: PreferenceParameterState? = null
fun getInsance(context: Context): PreferenceParameterState{
return instance ?: synchronized(this) {
instance ?: PreferenceParameterState(context)
}
}
}
}
@Composable
fun rememberPreferenceParameterState(): PreferenceParameterState {
val mContext= LocalContext.current
return remember {
PreferenceParameterState.getInsance(mContext)
}
}
Code B个
class PreferenceParameterState private constructor(context: Context) {
companion object {
@Volatile private var instance: PreferenceParameterState? = null
fun getInsance(context: Context): PreferenceParameterState{
if (instance == null) {
synchronized(this) {
if (instance == null) {
instance = PreferenceParameterState(context)
}
}
}
return instance!!
}
}
}
@Composable
fun rememberPreferenceParameterState(): PreferenceParameterState {
val mContext= LocalContext.current
return remember {
PreferenceParameterState.getInsance(mContext)
}
}