观察者模式代码详解
观察者模式的理解:
观察者模式就是、 某个人--->观察某件事件---》事情发生变化---》通知这个人---》去做某件事情
以下案例是腾讯公司发布订阅的小案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
</html>
<script>
function tengxun(){
this.订阅者们 = [];
this.发送 = function(){
var mes = this.message();
for(var i in this.订阅者们){
this.订阅者们[i].订阅(mes)
}
}
this.订阅频道 = function(qq){
this.订阅者们.push(qq);
}
this.message = function(){
return "来自腾讯的消息";
}
}
function QQ(qq){
this.qq = qq;
this.订阅 = function(mes){
console.log(this.qq+"您收到"+new Date()+mes)
}
}
var gongsi = new tengxun();
gongsi.订阅频道(new QQ("1234567"))
gongsi.订阅频道(new QQ("abcdfr"))
gongsi.订阅频道(new QQ("9087654"))
gongsi.订阅频道(new QQ("4564564"))
gongsi.发送();
</script>
结果:

浙公网安备 33010602011771号