03_装饰模式

这篇博客介绍了装饰器模式的实现,展示了如何通过装饰类增强`IStar`接口实现类的功能,如增加美丽和才艺。代码示例中,`BeautifulDecorator`负责装饰对象的美丽,而`TalentAndSkillDecorator`则增加了才艺。通过这两个装饰类,`YangChaoYue`对象可以在运行时动态地获得额外的能力。最后,博客提到了装饰模式与代理模式的区别。
摘要由CSDN通过智能技术生成

一、装饰类

package com.study.decorator

/**
 * 明星接口:
 * 基本要求:好看,有才艺
 */
interface IStar {
    fun beautiful()
    fun talentAndSkill()
}
package com.study.decorator

/**
 * 装饰抽象类
 */
abstract class Decorator(private val star: IStar) : IStar {
    override fun beautiful() {
        star.beautiful()
    }

    override fun talentAndSkill() {
        star.talentAndSkill()
    }
}
package com.study.decorator

/**
 * 负责装饰漂亮
 */
class BeautifulDecorator(star: IStar) : Decorator(star) {

    override fun beautiful() {
        makeUp()
        super.beautiful()
    }

    private fun makeUp() {
        println("通过化妆掩饰所有缺点,毕竟人无完人嘛")
    }
}
package com.study.decorator

/**
 * 才艺装饰
 */
class TalentAndSkillDecorator(star: IStar) : Decorator(star) {
    override fun talentAndSkill() {
        train()
        super.talentAndSkill()
    }

    /**
     * 才艺肯定是要先训练嘛
     */
    private fun train() {
        println("训练才艺,唱歌跳舞才能更吸引人嘛...")
    }
}

二、被装饰类

package com.study.decorator

class YangChaoYue : IStar {
    override fun beautiful() {
        println("长得好看")
    }

    override fun talentAndSkill() {
        println("唱歌跳舞")
    }
}

三、主程序调用

package com.study.decorator

/**
 * 装饰模式:
 * 可以有多个装饰类,被装饰类可以根据自己的需求来决定使用哪些装饰类对自己进行装饰
 *
 * 优点:装饰类可以动态的扩展被装饰类
 * 缺点:装饰层次过多时比较复杂,例如RxJava
 *
 *
 */
fun main() {
    val yangChaoYue = YangChaoYue()

    val beautifulDecorator = BeautifulDecorator(yangChaoYue)
    val talentAndSkillDecorator = TalentAndSkillDecorator(yangChaoYue)

    beautifulDecorator.beautiful()
    talentAndSkillDecorator.talentAndSkill()
}

四、运行结果

装饰器模式和代理模式的区别

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值