Appearance
代理模式
0、定义
TIP
1、使用者无权访问目标对象
2、中间加代理,通过代理做授权和控制
1、设计原则验证
- 1、代理类和目标类,隔离开目标类和使用者
- 2、符合开放封闭原则
2、示例
示例:翻墙上网、内网访问、明星经纪人

3、代码
js
class RealImg {
constructor(fileName) {
this.fileName = fileName
this.loadFromDisk() // 初始化即从硬盘中加载,模拟
}
display() {
console.log('display...' + this.fileName)
}
loadFromDisk() {
console.log('loading...' + this.fileName)
}
}
class ProxyImg {
constructor(fileName) {
this.realImg = new RealImg(fileName)
}
display() {
this.realImg.display()
}
}
let proxyImg = new ProxyImg('1.png')
proxyImg.display()4、经典场景
4.1、网页事件代理
4.2、jQuery $.proxy
js
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="div1">
<a href="#">a1</a>
<a href="#">a2</a>
<a href="#">a3</a>
<a href="#">a4</a>
<a href="#">a5</a>
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script type="text/javascript">
// 点击获取内容
// var div1 = document.getElementById('div1');
// div1.addEventListener('click', function(e) {
// if (target.nodeName === 'A') {
// alert(target.innerHTML)
// }
// })
//
//需求:点击改变背景颜色
// $('#div1').click(function() {
// setTimeout(function(){
// // this指向window,背景色不改变
// $(this).css('background-color', 'yellow')
// }, 1000)
// })
// 使用外部缓存this解决
// $('#div1').click(function() {
// var _this = this;
// setTimeout(function(){
// $(_this).css('background-color', 'yellow')
// }, 1000)
// })
// jQuery代理解决
$('#div1').click(function() {
var fn = function () {
$(this).css('background-color', 'yellow')
}
fn = $.proxy(fn, this)
setTimeout(fn, 1000)
// 合并$.proxy(function () {
// $(this).css('b
// setTimeout(ackground-color', 'yellow')
// }, this), 1000)
})
</script>
</body>
</html>4.3、ES6 Proxy
js
// 明星与经纪人
// 明星
let star = {
name: '张XXX',
age: 25,
phone: 'star: 13900001111'
}
// 经纪人
let agent = new Proxy(star, {
get: function(target, key) {
if (key === 'phone') {
// 返回经纪人自己的电话
return 'agent: 16899997777'
}
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
}
}
}
})
// test
console.log(agent.name)
console.log(agent.age)
console.log(agent.phone)
console.log(agent.price)
agent.customPrice = 150000
console.log('agent.customPrice', agent.customPrice)5、对比
代理模式 VS 适配器模式
- 适配器模式:提供一个不同的接口(如不同版本的插头)
- 代理模式:提供一摸一样的接口
代理模式 VS 装饰器模式
- 装饰器模式:扩展功能,原有功能不变且可直接使用
- 代理模式:显示原有功能,但是经过限制或者阉割之后的