Javascriptデザインパターンシステムの説明とアプリケーション-スタディノート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;
}

jsデコレータサードパーティライブラリ
core-decorators

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

設計原理の検証

  • 既存のオブジェクトとデコレータを分離すると、2つは独立して存在します
  • オープンおよびクローズド原則に準拠する

おすすめ

転載: blog.csdn.net/weixin_40693643/article/details/108820248