package SingleTon
import android.media.MediaPlayer
class AudioSingleManager private constructor(){
companion object ss{
private var instance: AudioSingleManager ? =null
get()
{
if(field == null)
{
field = AudioSingleManager ()
}
return field
}
fun GetInstance():AudioSingleManager {
return instance!!
}
}
}
这里举例获得一个单例对象,companion object一个类中只能有一个,且线程安全。
也可以使用
class SingletonDemo private constructor() {
companion object {
val instance: SingletonDemo by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
SingletonDemo() }
}
}