单例模式 → object 声明

11 阅读1分钟

单例模式 → object 声明

老写法(Java)

// 饿汉式
public class AppConfig {
    private static final AppConfig INSTANCE = new AppConfig();

    private AppConfig() {}

    public static AppConfig getInstance() { return INSTANCE; }

    public String getBaseUrl() { return "https://api.example.com"; }
}

// 懒汉式(双重检查)
public class LazyConfig {
    private static volatile LazyConfig instance;

    private LazyConfig() {}

    public static LazyConfig getInstance() {
        if (instance == null) {
            synchronized (LazyConfig.class) {
                if (instance == null) {
                    instance = new LazyConfig();
                }
            }
        }
        return instance;
    }
}

// 使用
String url = AppConfig.getInstance().getBaseUrl();

新写法(Kotlin)

// 饿汉式 — 一行
object AppConfig {
    val baseUrl = "https://api.example.com"
}

// 懒汉式
val lazyConfig: LazyConfig by lazy {
    LazyConfig()
}

// 使用
val url = AppConfig.baseUrl

一句话注意

object 声明的单例是线程安全的——Kotlin 编译器保证初始化在首次访问时执行且只执行一次。底层用的是 Java 的 static final 持有实例 + 同步块,等价于 DCL 但不用手写。

by lazy 的初始化也是线程安全的(默认 LazyThreadSafetyMode.SYNCHRONIZED),首次访问时执行 lambda 并缓存结果。如果确定是单线程访问,可以 lazy(LazyThreadSafetyMode.NONE) {} 省掉同步开销。


Java Android 老项目迁移系列,持续更新中。