装饰器模式

装饰器模式

1. 介绍

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

2. UML 演示

在这里插入图片描述

3. 代码演示

class Circle {
  draw() {
    console.log('画圆形')
  }
}
class Decorator {
  constructor(circle) {
    this.circle = new Circle()
  }

  draw() {
    this.circle.draw()
    this.setDecorator(circle)
  }
  setDecorator(circle) {
    console.log('设置为红色边框')
  }
}
//测试
let circle = new Circle()
circle.draw()
console.log('--------')
let decorator = new Decorator()
decorator.draw()

4. 场景

4.1 装饰类

@testDec
class Demo {
  //...
}
function testDec(target) {
  target.isDec = true
}
alert(Demo.isDec) //true
//装饰器原理
@decorator
class A {}

//等同于
class A {}
A = decorator(A) || A
//可以加参数
function testDec(isDec) {
  return function(target) {
    target.isDec = isDec
  }
}

@testDec(true)
class Demo {
  //...
}
alert(Demo.isDec) //true

4.2 mixin 示例

function mixins(...list) {
  return function(target) {
    Object.assign(target.proto, ...list)
  }
}

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

@mixins(Foo)
class MyClass {}

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

4.3 装饰方法(1)

class Person {
  constructor() {
    this.first = 'A'
    this.last = 'B'
  }
  //装饰方法
  @readonly
  name() {
    return `${this.first} ${this.last}`
  }
}

var p = new Person()
console.log(p.name())
// p.name = function() {} //会报错,因为name是只读属性
function readonly(target, name, descriptor) {
  // descriptor对象原来的值如下
  // {
  //   value: specifiedFunction,
  //   enumerable: false,
  //   configurable: true,
  //   writable: true
  // };
  descriptor.writable = false
  return descriptor
}

readonly(Person.prototype, 'name', descriptor)
// 类似于
Object.defineProperty(Person.prototype, 'name', descriptor)

4.4 装饰方法(2)

class Math {
  @log
  add(a, b) {
    return a + b
  }
}
let math = new Math()
const result = math.add(2, 4)
console.log(result)
function log(target, name, descriptor) {
  var oldValue = descriptor.value

  descriptor.value = function() {
    console.log(`Calling ${name} with`, arguments)
    return oldValue.apply(this, arguments)
  }
  return descriptor
}

4.5 core-decorators

  • 第三方开源 lib
  • 提供常用的装饰器
  • 点击此处查阅文档
//首先安装npm i core-decorators --save
import { readonly } from 'core-decorators'

class Person {
  @readonly
  name() {
    return 'zhang'
  }
}
let p = new Person()
alert(p.name())
//p.name = function(){//...} //此处会报错

5. 设计原则

  • 将现有对象和装饰器分离,两者独立存在
  • 符合开放封闭原则
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值