特点
1.使用者无法直接访问目标对象
2.使用者和目标对象之间加一层代理,通过代理来授权和控制
例如:访问github.com我们通常需要添加代理
class GitHubCon {
constructor(originIp) {
this.originIp = originIp
}
connect() {
console.log('正在通过'+ this.originIp + '连接github,网络连接不上')
}
}
class ProxyCon {
constructor(originIp) {
this.githubCon = new GitHubCon(originIp)
}
connect() {
console.log('经过网络代理过程逻辑后...')
this.githubCon.connect()
console.log('经过网络连接网络可访问')
}
}
let proxyCon = new ProxyCon('192.168.2.100')
proxyCon.connect()
//明细
let star = {
name: 'xuanleilei',
age: '27',
phone: '17372972684',
customPrice: 9999999
}
//经纪人
let agent = new Proxy(star, {
get: function(target, property) {
if(property == 'phone') {
//返回经纪人电话
return '18356086553'
}
if(property == 'price') {
return 8888888
}
return target[property]
},
set: function(target, property, value) {
if(property === 'customPrice') {
if(value < 1000000) {
throw new Error('价格太低')
} else {
target[property] = value
return true
}
}
}
})
//test
console.log(agent.name)
console.log(agent.price)
console.log(agent.phone)
agent.customPrice = 999
设计原则验证
1.代理类和目标类分离
2.符合开放封闭原则