线程安全的懒汉式
Java
java
public class Singleton{
private static Singleton instance;
private Singleton(){ }
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
kotlin
Kotlin
class Singleton private constructor(){
companion obejct{
private var instance:Singleton? = null
get(){
if(field == null) field = Singleton()
return field
}
@Synchronized
fun get():Singleton = instance!!
}
}