前言
基于JavaScript语言实现观察者模式。以家庭为应用背景,妈妈Lucy要去逛街,看到心仪的物品就会买下来。付钱???Lucy是不会付钱的,肯定是让爸爸Jack付钱啊。所以Jack要一直跟着Lucy逛街,Jack不喜欢逛街,Jack感到非常痛苦,但是又不能不跟着Lucy,万一Lucy想要买啥,没办法付钱咋办(盯着还能劝劝别上头,理性消费啊),Jack感到很头疼。
好家伙,Jack灵光一闪,想了个方法,Lucy买东西的时候通知一下我不就好了吗,为啥要一直跟着她逛街呢。
观察者模式
1 原型方法实现
var dad = function (name) {
this.name = name;
}
dad.prototype = {
// 付钱
pay: function () {
console.log("pay monny");
}
}
var mum = function (name) {
this.name = name;
// 设置通知谁付钱,也就是头头是谁
this.header = null;
}
mum.prototype = {
setHeader: function (header) {
this.header = header;
},
buy: function (thing) {
console.log(this.name + " buy " + thing);
// 买东西触发一些事件,付钱啦
this.notifyPay();
},
notifyPay: function () {
if (this.header) {
this.header.pay();
}
}
}
var son = function (name) {
this.name = name;
this.header = null;
};
son.prototype = {
setHeader: function (header) {
this.header = header;
},
buy: function (thing) {
console.log(this.name + " buy " + thing);
this.notifyPay();
},
notifyPay: function () {
if (this.header) {
this.header.pay();
}
}
}
2 如何使用
var jack = new dad('jack');
var lucy = new mum('lucy');
var mike = new son('mike');
lucy.setHeader(jack);
mike.setHeader(jack);
lucy.buy("bling bling.");
mike.buy('toy.');