package loaderman.bar class Singlenton private constructor(){ public var value:Singlenton?=null private object mHolder{ val INSTSNCE=Singlenton() } companion object Factory{ fun getInstance():Singlenton{ return mHolder.INSTSNCE } } }
package loaderman import loaderman.demo.Customer import loaderman.demo.Singlenton fun main(arg: Array<String>) { //Singlenton()//编译错误 由于主构造器使用private,无法直接调用主构造器 val instance1 = Singlenton.getInstance() val instance2 = Singlenton.getInstance() println(instance1) println(instance2) }
kotlin与Java实现方式不同主要在于kotlin类不支持静态方法和成员。由于kotlin支持全局函数和变量,因此可以直接使用全局函数和变量来代替静态方法和静态成员变量。