Kotlin实现单例模式

java 内部类实现

public class Single {

    private Single() {

    }

    public static Single getInstance() {
        return InnerSingle.Instance;
    }


    private static class InnerSingle {
        private static final Single Instance = new Single();
    }


}

kotlin object对象实现 方式一

class Single {
    private constructor()

    companion object {
        val instance: Single
            get() = InnerSingle.Instance
    }


    private object InnerSingle {
        val Instance = Single()
    }


}

kotlin 伴生对象实现 方式二

class Single {

    private constructor()

    companion object {
        fun getInstace(): Single {
            return HandleSingle.Instance
        }
    }

    private class HandleSingle {
        companion object {
            val Instance = Single()
        }
    }

}

你可能感兴趣的:(Kotlin实现单例模式)