装饰模式
装饰模式
对扩展开放,对修改关闭
情景
对于一个奶茶店的一个菜单,先定义一个基类,然后有那种饮料就继承基类。在该子类中计算饮料的价钱。这样子类就非常的多,不宜维护。,,,,
如果使用装饰模式就可以很好的解决这个问题。将饮料作为主题,给它添加装饰。
- 先看一下它的类图:
component:每一个被装饰者和装饰者都继承于它。
concretecomponent: 被装饰者,都继承于component,这样装饰者都可以给任何被装饰者添加该特定的行为。
decorator: 装饰者,持有一个component的对象(即是被装饰者),给它添加一些行为。
- 接着来实现一下上面的情形
component: (父类)
abstract class Beverage(){
var desc: String = "Unknown Beverage"
open fun getDescription() : String{
return desc
}
abstract fun cost(): Double
}
concretecomponent: (被装饰者)
class DarkRoast : Beverage { //..
constructor() {
desc = "DarkRoast"
}
override fun cost(): Double {
return .99
}
}
class HouseBlend : Beverage { //综合
constructor() {
desc = "House Blend Coffee"
}
override fun cost(): Double {
return .89
}
}
decorator: (装饰者)
abstract class CondimentDecorator : Beverage() { //调料
abstract override fun getDescription(): String
}
class Mocha : CondimentDecorator { //摩卡
private var beverage : Beverage
constructor(beverage: Beverage) {
this.beverage = beverage
}
override fun getDescription(): String {
return beverage.getDescription() + ", Mocha"
}
override fun cost(): Double {
return .20 + beverage.cost()
}
}
class Whip : CondimentDecorator { //..
private var beverage : Beverage
constructor(beverage: Beverage) {
this.beverage = beverage
}
override fun cost(): Double {
return beverage.cost() + .10
}
override fun getDescription(): String {
return beverage.getDescription() + ", Whip"
}
}
最后组织一下:
class Test {
companion object {
@JvmStatic
fun main(array: Array<String>) {
var beverage : Beverage = Espresso()
println(beverage.getDescription() + " $" + beverage.cost())
var beverage2 : Beverage = DarkRoast()
beverage2 = Mocha(beverage2)
beverage2 = Mocha(beverage2)
beverage2 = Whip(beverage2)
println(beverage2.getDescription() + " $" + beverage2.cost())
}
}
}