【Android,kotlin设计模式】Java的单例在Kotlin的5种实现
Kotlin.Java的单例在Kotlin的5种实现
1.饿汉式
2.懒汉式
3.线程安全的懒汉式
4.双重校验锁式
静态内部类式
1.饿汉式
Java
public class Singleton {
private static Singleton instance=new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return instance;
}
}
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
//方法一
class Singleton private constructor() {
companion object {
private var instance: Singleton? = null
get() {
if (field == null) {
field = Singleton()
}
return field
}
fun get(): Singleton{
return instance!!
}
}
}
//方法二
class Singleton private constructor() {
companion object {
private var instance: Singleton? = null
fun get(xx: String): Singleton{
if (instance== null) {
instance= Singleton(xx)
}
}
}
private constructor(xxx: String){
}
}
这里不用getInstance作为为方法名,是因为在伴生对象声明时,内部已有getInstance方法,所以只能取其他名字
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() {
companion object {
private var instance: Singleton? = null
get() {
if (field == null) {
field = Singleton()
}
return field
}
@Synchronized
fun get(): Singleton{
return instance!!
}
}
}
4.双重校验锁式
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()
}
}
}
//方式二
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 SingletonProvider{
private static Singleton instance=new Singleton();
}
private Singleton(){}
public static Singleton getInstance(){
return SingletonProvider.instance;
}
}
kotlin
class Singleton private constructor() {
companion object {
val instance = SingletonProvider.holder
}
private object SingletonProvider{
val holder= Singleton()
}
}
共有 0 条评论