代理模式很好理解,比如下面的送礼物示例,三个对象(小明,老王,小芳),小明想送礼物给暗恋的小芳,可是又害羞,只能拜托老王去送给小芳,老王就是代理,具体实现如下:
<!DOCTYPE html>
<html>
<head>
<meta chart="utf-8" />
<title>代理模式</title>
</head>
<body>
<script>
// 女孩类
var Girl = function (name) {
this.name = name;
this.getGift = function (boy, gift) {
console.log(this.name + "收到" + boy.name + "的心意,获得礼物:" + gift)
}
}
// 男孩类
var Boy = function (name, girl) {
this.name = name;
this.girl = girl;
console.log("我是" + this.name + ",我有个心愿想拜托老王实现")
this.sendGift = function (gift) {
console.log(this.name + "说:我想送给" + this.girl.name + gift)
}
}
// 代理类
var Proxy = function (boy) {
this.boy = boy;
this.proxySendGift = function (gift) {
console.log("老王接受请求,并倾听" + this.boy.name + "的心愿")
// 代理实现小明的心愿
this.boy.sendGift(gift);
console.log("老王帮助小明实现了心愿," + gift + "已经送出")
}
}
// 创建一个小明对象,并了解创建小明喜欢的对象小芳
var Xiaoming = new Boy("小明", new Girl("小芳"));
// 代理老王,帮助小明送出礼物
new Proxy(Xiaoming).proxySendGift("一束玫瑰花");
</script>
</body>
</html>