03_装饰模式

一、装饰类

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()
}

四、运行结果

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

猜你喜欢

转载自blog.csdn.net/Duckdan/article/details/109676852