1.懒汉模式
java
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return singleton;
}
}
kotlin
object Singleton{}
2.懒加载(非线程安全)
java
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
kotlin
// 1 //
class Singleton {
companion object {
val instance by lazy(LazyThreadSafetyMode.NONE) {
Singleton()
}
}
}
// 2 //
class Singleton {
private var instance: Singleton? = null
fun get(): Singleton {
if (instance == null) {
instance = Singleton()
}
return instance!!
}
}
3.懒加载(线程安全)
java
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
kotlin
class Singleton private constructor() {
private var instance: Singleton? = null
@Synchronized
fun get(): Singleton {
if (instance == null) {
instance = Singleton()
}
return instance!!
}
}
4.双重锁
java
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
instance = new Singleton();
}
}
return instance;
}
}
kotlin
// 1 //
class Singleton private constructor() {
companion object {
val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
Singleton()
}
}
}
// 2 //
class Singleton private constructor() {
private @Volatile var instance: Singleton? = null
fun get(): Singleton {
if (instance == null) {
synchronized(this) {
if (instance == null) {
instance = Singleton()
}
}
}
return instance!!
}
}
5.最优雅的写法:静态内部类
java
public class Singleton {
private static class Holder {
private static Singleton instance = new Singleton();
}
private Singleton() {
}
public static Singleton getInstance() {
return Holder.instance;
}
}
kotlin
class Singleton private constructor() {
companion object {
fun getInstance() = Holder.instance
}
private object Holder {
val instance = Singleton()
}
}
网友评论