现实的例子
假设你经营一家咖啡店,计算账单的时候需要根据添加的各种原料计算最终的成本,这个情况下,每个添加的原料可以作为装饰器
(实际上碰到这种例子,查表就可以了吧,价格不必硬编码到程序里)
简单总结
装饰器模式允许你通过用一个装饰器类包裹对象在运行时对一个对象动态添加行为
维基百科的解释
在面向对象编程中,装饰器模式是一种设计模式,它允许将行为静态或动态地添加到单个对象中,而不会影响来自同一类的其他对象的行为。decorator模式对于遵循单一职责原则通常很有用,因为它允许在具有唯一关注区域的类之间划分功能。
typescript example
下面时coffee例子的
interface Coffee {
getCost(): number
getDescription(): string
}
class SimpleCoffee implements Coffee {
getCost() {
return 10
}
getDescription() {
return 'simple coffee'
}
}
class MilkDecorator implements Coffee {
protected coffee: Coffee
protected description: string
constructor(c: Coffee) {
this.coffee = c
this.description = 'milk'
}
getCost() {
return 4 + this.coffee.getCost()
}
getDescription() {
return this.coffee.getDescription() + ' ' + this.description
}
}
class WhipDecorator implements Coffee {
protected coffee: Coffee
protected description: string
constructor(c: Coffee) {
this.coffee = c
this.description = 'whip'
}
getCost() {
return 5 + this.coffee.getCost()
}
getDescription() {
return this.coffee.getDescription() + ' ' + this.description
}
}
// 香草
class VanillaDecorator implements Coffee {
protected coffee: Coffee
protected description: string
constructor(c: Coffee) {
this.coffee = c
this.description = 'vanilla'
}
getCost() {
return 3 + this.coffee.getCost()
}
getDescription() {
return this.coffee.getDescription() + ' ' + this.description
}
}
const simpleCoffee = new SimpleCoffee()
console.log(simpleCoffee.getDescription())
console.log(simpleCoffee.getCost())
const milkCoffee = new MilkDecorator(simpleCoffee)
console.log(milkCoffee.getDescription())
console.log(milkCoffee.getCost())
const mixCoffee = new VanillaDecorator(
new MilkDecorator(new WhipDecorator(simpleCoffee))
)
console.log(mixCoffee.getDescription())
console.log(mixCoffee.getCost())
export{}
网友评论