zoukankan      html  css  js  c++  java
  • javascript设计模式——Observer

    定义一种一对多的从属关系,当一个目标状态改变,所有他的从属对对象都将收到通知。

    1.简单的Observer模式 实现

    var Observer = function(){
        this.list = [];
    }
    Observer.prototype.sub = function(func){
        this.list.push(func);
    }
    Observer.prototype.pub = function(msg){
        for(var i = 0; i<this.list.length; i ++){
            this.list[i](msg)
        }
    }
    Observer.prototype.unsub = function(func){
        var index = this.list.indexOf(func);
        this.list.splice(index,1);
    }
    var ob = new Observer();
    function func(msg){
        console.log(msg)
    }
    ob.sub(func);
    ob.pub("Hello");
    ob.unsub(func);
    ob.pub("useless");

     2.观察者模式应用

    在一个电子商务系统中,假设目前有三个类,分别是订单类,信息类,和检查类。在购买中,当下单之后要进行商品的检查,和商品信息发送。

    一般的做法是在订单类的下单完成函数里去构建其消息和检查类并调用其方法,这是一种耦合。

    而通过观察者模式,我们可以使用一个类去管理这些方法,当订单类状态发生改变时,其所有观察者都将收到通知,这里的观察者是其他类的函数,函数调用。

    //观察者模式实现的功能类
    var Observer = function(){
        this.list = [];
    }
    Observer.prototype.sub = function(func){
      // 主
    this.list.push(func); } Observer.prototype.pub = function(msg){ for(var i = 0; i<this.list.length; i ++){ this.list[i](msg) } } Observer.prototype.unsub = function(func){ var index = this.list.indexOf(func); this.list.splice(index,1); } var ob = new Observer(); //商品类 function Order(goods){ this.goods = goods; } Order.prototype.done = function(){ ob.pub(this.goods); } // 消息类 function Msg(){
      // 从 ob.sub(
    this.sendMsg); } Msg.prototype.sendMsg = function(goods){ alert(goods.name); } // 检查类 function Check(){
      //从 ob.sub(
    this.check); } Check.prototype.check = function(goods){ alert(goods.name != 0); } var order1 = new Order({'name':'耳机'}); var msg1 = new Msg(); var check1 = new Check(); order1.done()
  • 相关阅读:
    算法竞赛入门经典习题2-3 韩信点兵
    ios入门之c语言篇——基本函数——5——素数判断
    ios入门之c语言篇——基本函数——4——数值交换函数
    144. Binary Tree Preorder Traversal
    143. Reorder List
    142. Linked List Cycle II
    139. Word Break
    138. Copy List with Random Pointer
    137. Single Number II
    135. Candy
  • 原文地址:https://www.cnblogs.com/winderby/p/4318581.html
Copyright © 2011-2022 走看看