android public 简书,Android和Kotlin的单例写法

1、原始的单利方式(多线程并发,会重复new对象,不推荐使用)

Android

public class MyInstance {

private static MyInstanceinstance;

public static MyInstance getInstance(){

if(instance==null){

instance=new MyInstance();

}

return instance;

}

}

kotlin

class MyInstance {

companion object{

val instance by lazy(LazyThreadSafetyMode.NONE){

MyInstance()

}

}

}

2、添加线程锁(实现了单例,但是效率降低了,不推荐使用)

Android

public class MyInstance {

private static MyInstanceinstance;

public static synchronized MyInstance getInstance(){

if(instance==null){

instance=new MyInstance();

}

return instance;

}

}

Kotlin

class MyInstance {

companion object{

private var instance:MyInstance?=null

@Synchronized

fun get():MyInstance{

if(null==instance)instance=MyInstance()

return instance as MyInstance

}

}

}

3、双层加锁判断,并且线程安全(推荐使用)

public class MyInstance {

private static MyInstanceinstance;

public static MyInstance getInstance() {

if (instance ==null) {

synchronized (MyInstance.class) {

if(instance==null){

instance=new MyInstance();

}

}

}

return instance;

}

}

Kotlin

class MyInstance {

companion object{

val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED){

MyInstance()

}

}

}

4、内部类方式实现单例(推荐使用)

Android

public class MyInstance {

private static MyInstanceinstance;

public static MyInstance getsInstance() {

if (instance ==null) {

synchronized (MyInstance.class) {

if(instance==null){

instance=new MyInstance();

}

}

}

return instance;

}

}

Kotlin

class MyInstance {

companion object{

fun getInstance() = Helper.instance

}

private object Helper{

val instance = MyInstance()

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值