观察者模式的理解:

  观察者模式就是、 某个人--->观察某件事件---》事情发生变化---》通知这个人---》去做某件事情

  以下案例是腾讯公司发布订阅的小案例

<!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>

结果:
观察者模式代码详解

 


 

相关文章:

  • 2021-12-24
  • 2022-12-23
  • 2022-12-23
  • 2021-10-25
  • 2021-07-25
  • 2021-11-30
猜你喜欢
  • 2021-09-30
  • 2021-10-04
  • 2021-10-10
  • 2022-01-11
  • 2021-07-28
相关资源
相似解决方案