Kotlin單例寫法

Java 單例的寫法

public class Single {
    private static Single sInstance = null;

    private Single() {

    }

    public static Single getInstance() {
        if (sInstance == null) {
            sInstance = new Single();
        }
        return sInstance;
    }

    public void test() {
        
    }
}

Kotlin 單例的寫法

class KotSingle private constructor() {
    companion object {
        val instance: KotSingle by lazy { 
        		SingleonHolder.holder
         }
    }

    private object SingleonHolder {
        val holder = KotSingle()
    }

    fun test() {

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章