介绍
- 为对象添加新的功能
- 不改变原有的结构和功能
(手机壳)
UML类图
代码
class Circle {
draw() {
console.log('画了个圆')
}
}
class Decorator {
constructor(circle) {
this.circle = circle
}
draw() {
this.circle.draw()
this.setRedBorder(circle)
}
setRedBorder(circle) {
console.log('设置了circle边框颜色为red')
}
}
const circle = new Circle()
circle.draw()
const client = new Decorator(circle)
client.draw()
场景
- ES7 装饰器
- core-decorators
- 装饰器返回的是一个函数
以下:装饰类
@test
class Demo {
}
function test(target) {
target.isDec = true
}
alert(Demo.isDec);
function test(isDec) {
return function(target) {
target.isDec = isDec
}
}
@test(false)
class Demo {
}
alert(Demo.isDec);
function mixins(...list) {
return function(target) {
Object.assign(target.prototype, ...list)
}
}
const Foo = {
show() {
console.log('show')
}
}
@mixins(Foo)
class MyClass {}
const m = new MyClass()
m.show()
以下:装饰方法
function readonly(target, name, descriptor) {
descriptor.writable = false
console.log(descriptor)
return descriptor
}
class Person {
constructor() {
this.first = 'A'
this.last = 'B'
}
@readonly
name() {
return `${this.first} ${this.last}`
}
}
const p = new Person()
console.log(p.name())
// 错误
p.name = function() {
console.log(121)
}
console.log(p.name())
function log(target, name,descriptor) {
let oldVal = descriptor.value
descriptor.value = function() {
console.log(`此处为装饰器 打印 方法为${name}, 值为`, arguments)
return oldVal.apply(this, arguments)
}
return descriptor
}
class Demo {
@log
add(a, b) {
return a + b
}
}
const d = new Demo()
d.add(1,2)