js-代理模式

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适配器模式

  1. 适配器模式:提供一个不同的接口(有权用,功能不符合)
  2. 代理模式:提供一个一样的接口(无权用,代理用)

装饰器模式VS代理模式

装饰器模式:扩展功能,原有功能不变且可用

代理模式:针对原有功能,经过原有功能限制和阉割后


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值