Kotlin零基础学习 单例模式 object

2019-01-17  本文已影响11人  __素颜__

上篇文章中,大头儿子代理小头爸爸洗碗,中个代码漏洞,看下代码

/**
 * 洗碗接口
 * */
interface IWash {
    fun wash()
}

/**
 * 大头爸爸
 * */
class SmallFather : IWash by BigSon(){
    override fun wash() {
        println("小头爸爸让大头儿子洗碗")
        BigSon().wash()
        println("小头爸爸监督大头儿子洗碗,赚了9块钱")

    }
}

/**
 * 小头儿子
 * */
open class BigSon : IWash {
    override fun wash() {
        println("大头儿子洗碗每次1块钱")
    }

}

fun main(args: Array<String>) {
    var father = SmallFather();
    father.wash()

}

如果我们重复创建SmallFather类,SmallFather类中调用 BigSon().wash(),BigSon类也会重复创建,所以需要给BigSon写成单例模式,Kotlin中的单例很方便,单例类只需要用object修饰即可,Kolin中被object修饰的类,直接在jvm创建了,并且有且只有一个。

/**
 * 洗碗接口
 * */
interface IWash {
    fun wash()
}

/**
 * 大头爸爸
 * */
class SmallFather : IWash by BigSon {
    override fun wash() {
        println("小头爸爸让大头儿子洗碗")
        BigSon.wash()
        println("小头爸爸监督大头儿子洗碗,赚了9块钱")

    }
}

/**
 * 小头儿子
 * */
object BigSon : IWash {
    override fun wash() {
        println("大头儿子洗碗每次1块钱")
    }

}

fun main(args: Array<String>) {
    var father = SmallFather();
    father.wash()

}

注意:

1.单例类用object修饰去掉class。
2.单例类的接口代理,和创建 后面都不用接”()“。
3.单例类不可以被继承。

上一篇 下一篇

猜你喜欢

热点阅读