class ReadImg{
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 ReadImg(fileName)
}
display(){
this.realImg.display()
}
}
//test
let proxyImg = new ProxyImg("text.png")
proxyImg.display()
复制代码
前端常用举例
eg1
var div1 = document.getElementById('div1')
div1.addEventListener('click',function(){
var target = e.target
if(target.nodeName === 'A'){
alert(target.innerHTML)
}
})复制代码
eg2
$('#div1').click(function(){
setTimeout($.proxy(function(){
$(this).css('background-color','yellow')
},this),1000)
})复制代码
demo
let star = {
name : '张xx'
age : 25
phone : 'star:231321'
}
let agent = new Proxy(star,{
get: function(target,key){
if(key === 'phone'){
return 'agent : 123532'
}
if(key === 'price'){
return 1200000
}
return target[key]
},
set: function(target, key, val){
if(key === 'customPrice'){ //业务逻辑:报价,非价格price
if(val < 100000){
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 = 90000
console.log('agent.customePrice',agent.customPrice)复制代码
-----------------------------------------------------------------------------------
代理模式VS适配器模式
- 适配器模式:提供一个不同的接口(有权用,功能不符合)
- 代理模式:提供一个一样的接口(无权用,代理用)
装饰器模式VS代理模式
装饰器模式:扩展功能,原有功能不变且可用
代理模式:针对原有功能,经过原有功能限制和阉割后