美文网首页
装饰器模式 - 演示与场景

装饰器模式 - 演示与场景

作者: EmilWong | 来源:发表于2019-06-10 10:40 被阅读0次
  • 为对象添加新功能
  • 不改变其原有的结构和功能

UML类图:


image.png
class Circle{
    draw() {
        console.log('画一个圆形')
    }
}
class Decorator {
    constructor(circle){
        this.circle = circle
    }
    draw() {
        this.circle.draw()
        this.setRedBorder(circle)
    }
    setRedBorder(circle){
        console.log('设置红色边框')
    }
}
// 测试代码
let circle = new Circle()
circle.draw() // 画一个圆形

let decorator = new Decorator(circle)
decorator.draw() // 画一个圆形 设置红色边框

使用场景:
core-decorators

readonly 
import { readonly } from 'core-decorators'
class Person{
  @readonly
  name() {
    return name
  }
}

API 下一个版本弃用

import { deprecate } from 'core-decorators'
class Person{
  @deprecate
  name() {
    return 'Emil'
  }
}

设计原则验证

  • 将现有对象和装饰器进行分离,两者独立存在
  • 符合开放封闭原则

相关文章

网友评论

      本文标题:装饰器模式 - 演示与场景

      本文链接:https://www.haomeiwen.com/subject/yueaxctx.html