介绍
- 使用者无权访问目标对象
- 中间加代理,通过代理做授权和控制
示例
UML类图
点击查看【processon】
代码
// 明星let star = { name: '张XX', age: 25, phone: '13910733521'}// 经纪人let agent = new Proxy(star, { get: function (target, key) { if (key === 'phone') { // 返回经纪人自己的手机号 return '18611112222' } if (key === 'price') { // 明星不报价,经纪人报价 return 120000 } return target[key] }, set: function (target, key, val) { if (key === 'customPrice') { if (val < 100000) { // 最低 10w throw new Error('价格太低') } else { target[key] = val return true } } }})// 主办方console.log(agent.name)console.log(agent.age)console.log(agent.phone)console.log(agent.price)// 想自己提供报价(砍价,或者高价争抢)agent.customPrice = 150000// agent.customPrice = 90000 // 报错:价格太低console.log('customPrice', agent.customPrice)
场景
- $.proxy```javascript$("#d1").click(function() { const fn = function() { setTimeout($.proxy(function() { // this 符合期望 $(this).addClass('d2') }, this), 1000) }})// =>>$("#d1").click(function() { let fn = function() { $(this).addClass('d2') } fn = $.proxy(fn, this) setTimeout(fn, 1000)})
代理模式和适配器模式比较
- 适配器模式:提供不同的接口(如不同版本的插头)
- 代理模式:提供一摸一样的接口
代理模式和装饰器模式比较
- 装饰器模式:扩展功能,原有功能不变而且可直接使用(手机的手机壳)
- 代理模式:显示原有功能,但是是经过限制和阉割之后的