Skip to content

装饰者模式 ​

装饰者模式可在不改变对象自身的基础上,动态地给对象添加新功能。适用于灵活扩展对象功能而不希望修改源对象的场景。

代理模式通常只有一层代理,而装饰者模式常会经常一条长的装饰链。

AOP 数据统计上报 ​

showPopper 函数职责不单一,既负责打开浮层,又负责数据上报。

js
function log() {
  console.log('数据上报')
}

function showPopper() {
  console.log('打开浮层')
  log()
}

showPopper()

可用装饰者模式为 Function 原型添加 after 方法,这样 showPopper 和 log 的职责就变单一,且可根据需求来选择使用 showPopper 或 showPopperAndLog。

js
function log() {
  console.log('数据上报')
}

function showPopper() {
  console.log('打开浮层')
}
  
Function.prototype.after = function (fn) {
  return (...args) => {
    const result = this.apply(this, args)
    fn.apply(this, args)
    return result
  }
}

const showPopperAndLog = showPopper.after(log)
showPopperAndLog()

AOP 动态修改函数参数 ​

ajax 为发起请求的函数,在不修改 ajax 函数代码的情况下为请求添加 token。

移植到其他项目时,可能有的接口不需要 token,可能 token 生成方式不一样,不管是哪种情况,都可在不修改原 ajax 函数的情况下,为其动态装饰上 token 参数,保证 ajax 是个相对纯净的函数,提高其可复用性。

js
function ajax(type, url, params) {
  console.log(params)
  // ...
}

Function.prototype.before = function (fn) {
  return (...args) => {
    fn.apply(this, args)
    return this.apply(this, args)
  }
}

const tokenAjax = ajax.before(function (type, url, params) {
  params.token = 'xxx' // 为params参数添加token
})

ajax('post', 'https://example.com', {name: 'Jay'})      // { name: 'Jay' }
tokenAjax('post', 'https://example.com', {name: 'Jay'}) // { name:'Jay', token: 'xxx' }

不污染原型 ​

以上 AOP 是在 Function.prototype 上添加 before 和 after,但一般不建议修改原型,所以可做些变通,将原函数和新函数都作为参数传入。

js
function before(fn, beforeFn) {
  return function (...args) {
    beforeFn.apply(this, args)
    return fn.apply(this, args)
  }
}