1.介绍
装饰者模式:为对象添加新功能,不改变原有的结构和功能,装饰者模式体现了开闭原则。
UML类图
简化
class Circle(){
draw(){
console.log('画一个圆形')
}
}
class Decorator(){
constructor(circle){
this.circle = circle
}
setRedBorder(circle){
console.log('设置红色边框')
}
draw(){
this.circle.draw();
this.setRedBorder(circle);
}
}
2.场景
ES7装饰器
(1)
@test
class Demo{
}
function test(target){
target.isDec = true
}
等同于
@decorator
classs A {}
A = decorator(A) || A
(2)带参数
function test(isDec){
reteurn function(target){
target.isDec = isDec
}
}
@testDec(false)
class Demo{
}
core-decorators
开源库