Skip to content
This repository has been archived by the owner on Aug 7, 2024. It is now read-only.

设计模式之「结构型模式」 #26

Open
1 of 7 tasks
fi3ework opened this issue Jun 28, 2018 · 1 comment
Open
1 of 7 tasks

设计模式之「结构型模式」 #26

fi3ework opened this issue Jun 28, 2018 · 1 comment

Comments

@fi3ework
Copy link
Owner

fi3ework commented Jun 28, 2018

  • 外观模式/门面模式(Facade)
  • 适配器模式(Adapter)
  • 代理模式(Proxy)
  • 装饰模式(Decorator)
  • 桥接模式(Bridge)
  • 组合模式(Composite)
  • 享元模式(Flyweight)
@fi3ework
Copy link
Owner Author

fi3ework commented Jul 6, 2018

代理模式

代理模式的主要意义是实现功能的解耦,即满足单一职责原则,可以简单的理解为在某个满足单一职责的类外面用与之相同的接口对它包裹一层,进而实现对原类的增强。

React 中的高阶组件(这里专指属性代理高阶组件)其实就是代理的一种应用,所以也被更准确的叫做属性代理的高阶组件,高阶组件定义与被代理组件一致的 props,这也是实现代理模式的关键 —— 代理和本体接口的一致性。

代理其实可以说是在不修改被代理对象的前提下对被代理对象的加强。

实现

代码实现

// plus function
const plus = (...args) => {
  return args.reduce((accu, curr) => {
    return accu + curr
  }, 0)
}

// mult function
const mult = (...args) => {
  return args.reduce((accu, curr) => {
    return accu * curr
  }, 1)
}

// proxy factory
const createProxyFactory = (fn) => {
  let cache = {}
  return (...args) => {
    let argsId = args.join(',')
    if (Object.keys(cache).indexOf(argsId) >= 0) {
    	console.log('read from cache')
      return cache[argsId]
    }
    return cache[argsId] = fn.apply(this, args)
  }
}

const proxyPlus = createProxyFactory(plus)
const proxyMult = createProxyFactory(mult)

let m1 = console.log(proxyMult(2, 3, 4)) // 24
let m2 = console.log(proxyMult(2, 3, 4)) // read from cache 24
let p1 = console.log(proxyPlus(2, 3, 4)) // 9
let p2 = console.log(proxyPlus(2, 3, 4)) // read from cache 9

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

1 participant