Java的单例在Kotlin的5种实现
- 饿汉式
- 懒汉式
- 线程安全的懒汉式
- 双重校验锁式
- 静态内部类式
饿汉式
Java
public class Singleton {
private static Singleton instance=new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return instance;
}
}
Kotlin
object Singleton
懒汉式
Java
public class Singleton {
private static Singleton instance;
private Singleton(){
}
public static Singleton getInstance(){
if(instance==null){
instance=new SingletonDemo();
}
return instance;
}
}
Kotlin
class Singleton private constructor() {
companion object {
private var instance: Singleton? = null
get() {
if (field == null) {
field = Singleton()
}
return field
}
fun get(): Singleton{
return instance!!
}
}
}
//or
class Singleton private constructor() {
companion object {
private var instance: Singleton? = null
fun get(xx: String): Singleton{
if (instance== null) {
instance= Singleton(xx)
}
}
}
constructor(xxx: String){
}
}
这里不用getInstance作为为方法名,是因为在伴生对象声明时,内部已有getInstance方法,所以只能取其他名字
线程安全的懒汉式
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() {
companion object {
private var instance: Singleton? = null
get() {
if (field == null) {
field = SingletonDemo()
}
return field
}
@Synchronized
fun get(): SingletonDemo{
return instance!!
}
}
}
双重校验锁式
Java
public class Singleton {
private volatile static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null){
synchronized (Singleton.class){
if(instance==null){
instance=new Singleton();
}
}
}
return instance;
}
}
kotlin
class Singleton private constructor() {
companion object {
val instance: Singleton by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
Singleton()
}
}
}
or
class Singleton private constructor(private val xxx: String) {//这里可以根据实际需求发生改变
companion object {
@Volatile
private var instance: Singleton? = null
fun getInstance(xx: String) =
instance ?: synchronized(this) {
instance ?: Singleton(xx).also { instance = it }
}
}
}
静态内部类式
Java
public class Singleton {
private static class SingletonHolder{
private static Singleton instance=new Singleton();
}
private Singleton(){}
public static SingletonDemo getInstance(){
return SingletonHolder.instance;
}
}
kotlin
class Singleton private constructor() {
companion object {
val instance = SingletonHolder.holder
}
private object SingletonHolder {
val holder= SingletonDemo()
}
}