对象结构型模式——装饰者模式(decorator)
来源:互联网 发布:java游戏开发工程师 编辑:程序博客网 时间:2024/06/05 22:53
- 定义:
动态的给对象添加一些额外的职责。就增加功能来说,装饰者模式提供了比继承更加有弹性的另一种方案。 - 概述:
装饰者模式可以透明的给对象增加功能,并实现功能的组合。被装饰的对象可以已经被装饰过多次,在Java中I/O是装饰者模式的典型代表之一。 - 实例(Kotlin语言)
被装饰者的抽象类:饮料类
abstract class Beverage { //给一个默认的饮料名 open var description = "Unknown Beverage" //给一个默认的饮料的价格 open fun cost(): Double { return 0.0 }}
被装饰的类,饮料的一种:浓咖啡类
class Espresso : Beverage() { override var description: String get() = "Espresso" set(value) {} override fun cost(): Double { return 1.99 }}
装饰者的抽象类,调味类
abstract class CondimentDecorator : Beverage { val beverage: Beverage constructor(beverage: Beverage) { this.beverage = beverage } override var description: String get() = beverage.description set(value) { beverage.description = value } override fun cost(): Double { return beverage.cost() }}
具体的装饰类:摩卡Mocha类
class Mocha(beverage: Beverage) : CondimentDecorator(beverage) { override var description: String get() = beverage.description + ",Mocha" set(value) {} override fun cost(): Double { return 0.2 + beverage.cost() }}
具体的装饰类:奶油Whip类
class Whip(beverage: Beverage) : CondimentDecorator(beverage) { override var description: String get() = beverage.description + ",whip" set(value) {} override fun cost(): Double { return 0.5 + beverage.cost() }}
测试类及测试结果
fun main(args: Array<String>) { //未被装饰过的浓咖啡 val espresso = Espresso() println("我要一杯浓咖啡(espresso)"+"--描述:"+espresso.description+";钱:"+espresso.cost()) //用摩卡装饰过的咖啡 val mocha = Mocha(espresso) println("我要一杯加了摩卡(mocha)的浓咖啡(espresso)--"+"--描述:"+mocha.description+";钱:"+mocha.cost()) //用奶油装饰过的摩卡咖啡 val whip = Whip(mocha) println("我要一杯加了摩卡(mocha)和奶油(whip)味的浓咖啡(espresso)"+"--描述:"+whip.description+";钱:"+whip.cost())}//测试结果我要一杯浓咖啡(espresso)--描述:Espresso;钱:1.99我要一杯加了摩卡(mocha)的浓咖啡(espresso)----描述:Espresso,Mocha;钱:2.19我要一杯加了摩卡(mocha)奶油(whip)味的浓咖啡(espresso)--描述:Espresso,Mocha,whip;钱:2.69Process finished with exit code 0
- 类图
如有错误,请留言更正,或进580725421群讨论,以免误导其他开发者!!!
阅读全文
0 0
- 对象结构型模式——装饰者模式(decorator)
- 装饰模式(Decorator)-对象结构型模式
- 装饰(Decorator)——对象结构型模式
- 设计模式之十四:Decorator(装饰)—对象结构型模式
- 装饰模式(Decorator)---对象结构型模式
- Decorator 装饰对象结构模式
- 结构型模式-----装饰模式(decorator)
- Decorator模式(装饰模式 结构型)
- Java装饰模式(Decorator)—结构型
- 2.4 Decorator(装饰) -- 对象结构型模式
- 设计模式 (三)——装饰者模式(Decorator,结构型)
- 【design pattern】结构型模式之—装饰者模式(Decorator)
- 结构型模式之装饰者模式(Decorator)
- 结构型模式:DECORATOR——装饰模式
- JAVA设计模式(7) —<结构型>装饰模式(Decorator)
- 结构型-装饰者模式(decorator)
- Decorator 装饰(结构型模式)
- 结构型模式:Decorator(装饰)
- 承受不了风险,注定只能平庸
- Maximum Subsequence Sum
- Arcgis For Android 查询功能
- 运维知识内容
- Java
- 对象结构型模式——装饰者模式(decorator)
- JavaWeb常用功能-文件下载
- SQL查询结果ToDataTable
- Freemarker中通过request获得contextPath
- Kotlin入门
- Java处理导入excel文件的解决思路和方案
- List-Reverse List
- 手机升级版本到ios11导致无法调试
- Mybatis通用Mapper的使用