通用设计模式之代理模式(Proxy)

代理模式(Proxy)为对象提供另一个代理对象以控制对这个对象的访问。

使用代理的原因是我们不想对原对象进行直接操作,而是通过一个“中间人”来传达操作。生活中有许多代理的例子,比如访问某个网站,不想直接访问,通过中间的一台服务器来转发请求,这台服务器就是代理服务器。又比如明星,普通人无法直接联系他们,而是通过经纪人进行联系。

使用ES6的Proxy语法实现对代理模式的简单实现:

let star = {
  name:'zs',
  age:21,
  height:170,
  bottomPrice:100000,
  announcements:[],
}
let proxy = new Proxy(star,{
  get:function (target,key) {
    if(key === 'height'){
      return target.height + 10
    }else if(key === 'announcements'){
      return new Proxy(target.announcements,{
        set:function (target,key,value) {
          if(key !== 'length' && target.length === 3){
            console.log('不好意思,今年通告满了')
            return true
          }
          target[key] = value
          return true
        }
      })
    }else{
      return target[key]
    }
  },
  set:function (target, key, value,) {
    if(key === 'price'){
      if(value > target.bottomPrice * 1.5){
        console.log('成交');
        target.price = value
      }else if(value > target.bottomPrice){
        console.log('咱们再商量商量');
      }else {
        throw new Error('下次说吧')
      }
    }
  }
})

proxy.announcements.push('爸爸去哪儿')
proxy.announcements.push('中国好声音')
proxy.announcements.push('奇葩说')
proxy.announcements.push('快乐大本营')
proxy.price = 160000
proxy.price = 120000
proxy.price = 9000

代理模式能将代理对象与被调用对象分离,降低了系统的耦合度。代理模式在客户端和目标对象之间起到一个中介作用,这样可以起到保护目标对象的作用。代理对象也可以对目标对象调用之前进行其他操作。

示例:dom事件代理 。Vue源码。

注意区分适配器模式(Adapter),装饰器模式(Decorator),代理模式(Proxy):

适配器模式提供不同的新接口,通常用作接口转换的兼容处理

代理模式提供一模一样的新接口,对行为进行拦截

装饰器模式,直接访问原接口,直接对原接口进行功能上的增强

posted @ 2020-04-01 20:03  午亭爱成长  阅读(193)  评论(0编辑  收藏  举报