kotlin单例模式(3)

线程安全的懒汉式

Java

java 复制代码
public class Singleton{
    private static Singleton instance;
    private Singleton(){ }
    public static synchronized Singleton getInstance(){
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}

kotlin

Kotlin 复制代码
class Singleton private constructor(){
    companion obejct{
        private var instance:Singleton? = null
        get(){
            if(field == null) field = Singleton()
            return field
        }
        @Synchronized
        fun get():Singleton = instance!!
    }
}
相关推荐
程序员清风2 小时前
程序员兼职必看:靠谱软件外包平台挑选指南与避坑清单!
java·后端·面试
皮皮林5513 小时前
利用闲置 Mac 从零部署 OpenClaw 教程 !
java
A0微声z5 小时前
Kotlin Multiplatform (KMP) 中使用 Protobuf
kotlin
华仔啊8 小时前
挖到了 1 个 Java 小特性:var,用完就回不去了
java·后端
SimonKing9 小时前
SpringBoot整合秘笈:让Mybatis用上Calcite,实现统一SQL查询
java·后端·程序员
alexhilton19 小时前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
日月云棠1 天前
各版本JDK对比:JDK 25 特性详解
java
用户8307196840821 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
JavaGuide1 天前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
IT探险家1 天前
Java 基本数据类型:8 种原始类型 + 数组 + 6 个新手必踩的坑
java