• js 设计模式之观察者模式


    观察者模式 又被称为“发布-订阅”模式,目的是解决主题对象和观察者之间功能的耦合性。发布者和订阅者之间是互不干扰的,没有联系的,通过观察者,当做中介,将二者联系起来。

    例子:以学生和老师之间的为例

    1.首先创建观察者对象

    //将观察者放在闭包中,当页面加载就立即执行
    var Observer = (function () {
    //防止消息队列暴露而被篡改顾将消息容器作为静态私有变量保存
    var _message = {};
    return {
    //注册信息接口
    regist: function () {},
    //发布信息接口
    fire: function () {},
    // 移除信息接口
    remove:function () {}
    }
    }) ()

    2.创建学生类以及有关方法

    //学生类
    var Student = function(result) {
    var that = this;
    that.result = result;
    // 学生回答问题动作
    that.say = function() {
    console.log(that.result);
    }
    }
    //学生回答问题的方法
    Student.prototype.answer = function(question) {
    // console.log(this.result +''+ question + '回答问题')
    //注册参数问题
    Observer.regist(question, this.say)
    }
    // 学生睡觉 ,此时不能回答问题的方法
    Student.prototype.sleep = function(question) {
    console.log(this.result +''+ question + '已被注销')
    //取消对老师问题的监听
    Observer.remove(question, this.say)
    }

    3.创建教师类和有关方法

    //教师类
    var Teacher = function () {};
    //教师提问问题的方法
    Teacher.prototype.ask = function (question) {
    console.log('问题是:' + question);
    //发布提问消息
    Observer.fire(question)
    }

    4.创建实体类

    /模拟3位听课的学生
    var student1 = new Student('学生1回答问题'),
    student2 = new Student('学生2回答问题'),
    student3 = new Student('学生3回答问题');

    //3位学生监听(订阅)了老师提出的两个问题
    student1.answer('什么是设计模式1');
    student1.answer('简述观察者模式1');
    student2.answer('什么是设计模式2');
    student2.answer('简述设计者模式2');
    student3.answer('什么是设计模式3');
    student3.answer('简述观察者模式3');

    //第三位同学 因为睡着了,取消了订阅的第二个问题
    student3.sleep('简述观察者模式3');

    //创建一个教师类
    var teacher = new Teacher();
    //老师 提问两个问题
    teacher.ask('什么是设计模式');
    teacher.ask('简述观察者模式');

  • 相关阅读:
    uoj310. 【UNR #2】黎明前的巧克力
    ZJOI2015 幻想乡战略游戏
    bzoj4407 于神之怒加强版
    bzoj3309 DZY Loves Math
    CF613D Kingdom and its Cities
    bzoj3677 [Apio2014]连珠线
    CF961G Partitions
    loj6077. 「2017 山东一轮集训 Day7」逆序对
    bzoj4596 [Shoi2016]黑暗前的幻想乡
    CF786B/CF787D Legacy
  • 原文地址:https://www.cnblogs.com/mn6364/p/8847568.html
Copyright © 2020-2023  润新知