자바 스크립트 디자인 패턴 시스템 설명 및 적용 —— 연구 노트 5 장식 패턴

데코레이터 모드

  • 개체에 새로운 기능 추가
  • 원래 구조와 기능을 변경하지 않습니다.

여기에 사진 설명 삽입

class Circle {
    
    
  draw() {
    
    
    console.log('画一个圆形')
  }
}

class Decorator {
    
    
  constructor(circle) {
    
    
    this.circle = circle
  }
  draw() {
    
    
    this.circle.draw()
    this.setRedBord(circle)
  }
  setRedBord(circle) {
    
    
    console.log('设置红色边框')
  }
}

// 测试
let circle = new Circle()
circle.draw()
let dec = new Decorator(circle)
dec.draw()

장면

  • ES7 데코레이터
  • core-decorators
ES7 데코레이터

장식


@testDec
class Demo {
    
    
  // ...
}

function testDec(target) {
    
    
  target.isDec = true;
}

alert(Demo.isDec) // true

매개 변수 형식 :

function testDec(isDec) {
    
    
  return funciton (target) {
    
    
    target.isDec = isDec
  }
}
@testDec(false)
class Demo {
    
    

}
alert(Demo.isDec)  // false

데코레이터-믹신 예제

function mixin(...list) {
    
    
  return function (target) {
    
    
    Object.assign(target.prototype, ...list)
  }
}

const Foo = {
    
    
  foo() {
    
     alert('foo') }
}

@mixins(Foo)
class MyClass {
    
    }

let obj = new MyClass()
obj.foo() // 'foo'

장식 방법

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 () {
    
    }  // 报错,因为name是只读属性

@readonly실현

function readonly(target, name, descriptor) {
    
    
  // descriptor 属性描述对象, Object.defineProperty中会用到, 原来的值如下;
  // {
    
    
  //   value: specifiedFunction,
  //   enumerable: false,   // 可枚举
  //   configurable: true,  // 可配置
  //   writable: true       // 可写
  // }
  descriptor.writable = false  // 变为不可写
  return descriptor
}

장식 방법

class Math {
    
    
  // 装饰方法
  @log
  add(a, b) {
    
    
    return a + b
  }
}

const math = new Math()
const result = math.add(2, 4) // 执行add时,会自动打印日志,因为有@log装饰器
console.log('result', result)

@log 데코레이터 메서드 구현

function log(target, name, descriptor) {
    
    
  let oldValue = descriptor.value;  // zhuan shi
  descriptor.value = function() {
    
    
    console.log(`Calling ${
      
      name} with`, arguments)
    reutrn oldValue.apply(this, arguments)
  };
  return descriptor;
}

Node.js 데코레이터 타사 라이브러리 라이브러리
core-decorators

import {
    
     deprecate } from 'core-decorators'   // 提示废弃

설계 원리 검증

  • 기존 객체와 데코레이터를 분리하면 두 가지가 독립적으로 존재합니다.
  • 개방 및 폐쇄 원칙 준수

추천

출처blog.csdn.net/weixin_40693643/article/details/108820248