你好世界
  • 入门
  • 框架
  • Webpack
  • 模式
  • 知识点
  • 面试题
  • Koa
  • Java
  • Python
  • MongoDB
  • Redis
  • Algorithm
  • AI 概述
  • 机器学习
  • 深度学习
  • 自然语言处理
  • 关键词说明
  • 使用技巧
  • 本地模型安装及下载
  • 调试
  • 测试
  • GIT
  • Network
  • Linux
  • VSCode
  • GitHub
  • Mock
  • 入门
  • 框架
  • Webpack
  • 模式
  • 知识点
  • 面试题
  • Koa
  • Java
  • Python
  • MongoDB
  • Redis
  • Algorithm
  • AI 概述
  • 机器学习
  • 深度学习
  • 自然语言处理
  • 关键词说明
  • 使用技巧
  • 本地模型安装及下载
  • 调试
  • 测试
  • GIT
  • Network
  • Linux
  • VSCode
  • GitHub
  • Mock
  • DesignMode

    • 设计模式
    • 面向对象
    • UML 类图
    • 设计原则
    • 面试题分析
    • 工厂模式
    • 单例模式
    • 适配器模式
    • 装饰器模式
    • 代理模式
    • 外观模式(网关?)
    • 观察者模式
    • 迭代器模式
    • 状态模式
    • 其它设计模式
  • SoftwareArchitecturePatterns

    • SoftwareArchitecturePatterns (软件架构模式)
    • MVVC
    • MVC
    • MVP

装饰器模式

介绍

  • 为对象添加新功能;
  • 不改变其原有的结构和功能;

设计原则验证

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

示例

示例-7
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 dec = new Decorator(circle);
dec.draw()

场景

  • ES7装饰器
    • 配置环境
    // npm i babel-plugin-transform-decorators-legacy -D
    // .babelrc
    {
      "presets": ["es2015", "latest"],
      "plugins": ["transform-decorators-legacy"]
    }
    // jsconfig.json
    {
      "compilerOptions": {
        "experimentalDecorators": true
      },
    }
    
    • 装饰类
    @decorator
    class A {};
    // 等同于 
    class A {};
    A = decorator(A) || A;
    
    • 装饰方法
    function readonly(target, name, descriptor) {
      descriptor.writable = false
      return descriptor
    }
    class Person {
      constructor() {
        this.first = 'A'
        this.last = 'B'
      }
      @readonly
      name(){
        return`${this. first} ${this.last} `
      }
    }
    let p = new Person()
    console.log(p.name())
    p.name = "" // 会报错
    
  • core-decorators
    • 第三方开源 lib
    • 提供常用的装饰器
最后更新时间: 3/7/22, 9:11 PM
贡献者: DESKTOP-ER5718D\zt
Prev
适配器模式
Next
代理模式