在java中,我们可以使用双重Checked Locking&volatile编写thead-safe单例:
public class Singleton {
private static volatile Singleton instance;
public static Singleton getInstance(String arg) {
Singleton localInstance = instance;
if (localInstance == null) {
synchronized (Singleton.class) {
localInstance = instance;
if (localInstance == null) {
instance = localInstance = new Singleton(arg);
}
}
}
return localInstance;
}
}
Run Code Online (Sandbox Code Playgroud)
我们怎么能用kotlin写呢?
object A {
object B {}
object C {}
init {
C.hashCode()
}
}
Run Code Online (Sandbox Code Playgroud)
我使用kotlin反编译器来实现
public final class A {
public static final A INSTANCE;
private A() { …Run Code Online (Sandbox Code Playgroud)