资讯专栏INFORMATION COLUMN

js设计模式之观察者模式和发布/订阅模式

HitenDev / 707人阅读

摘要:添加获取长度获取下标通知首先我们声明一个主体类,里面包含一个观察者数组,还有一些操作方法。观察者通用声明一个更新接口,用来获取主体分发的通知。主体分发消息给观察者。

观察者模式
The Observer is a design pattern where an object (known as a subject) maintains a list of objects depending on it (observers), automatically notifying them of any changes to state.

观察者是一种 包含一系列依赖于主体(subject)的观察者(observers),自动通知它们变化的内容的设计模式

接下来,用oberver pattern来实现一个购物车列表,实现之前先说明几个概念:

主体 (Subject)

维护一系列观察者的数组,包含一些操作方法,比如增加、删除,获取等等。
class Subject {
    constructor() {
        this.observerList = [];
    }
    add(item) { //添加
        return this.observerList.push(item);
    }
    count() { //获取长度
        return this.observerList.length;
    }
    get(index) { //获取下标
        if (index > -1 && index < this.observerList.length) {
            return this.observerList[index];
        } else {
            return null;
        }
    }
    notify(context) { //通知
        let observerCount = this.count();

        for (let i = 0; i < observerCount; i++) {
            console.dir(this.get(i))
            this.get(i).update(context);
        }
    }
}

首先我们声明一个主体类,里面包含一个观察者数组,还有一些操作方法。

观察者(Observer)

class Observer {
    constructor() {
        this.update = () => { //通用interface
            //todo
        }
    }
}

声明一个更新接口,用来获取主体分发的通知。

两者关系大概如下:

主要流程:

定义好主体类和观察者类

类实例化成具体对象,绑定方法,观察者在主体对象里注册

操作。主体分发消息给观察者。

具体实现代码如下:





    
    
    
    Document
    



    

name: price:

list
name price action
发布/订阅者模式
The Publish/Subscribe pattern however uses a topic/event channel which sits between the objects wishing to receive notifications (subscribers) and the object firing the event (the publisher). This event system allows code to define application specific events which can pass custom arguments containing values needed by the subscriber. The idea here is to avoid dependencies between the subscriber and publisher.

Publish/Subscribe pattern和Observer pattern和类似,都是Observer注册,subject分布通知,但是Publish/Subscribe pattern多了个事件管道(event channel)用来集中处理监听的事件

典型的Publish/Subscribe模式的实现代码:

var pubsub = {};
        (function(myObject) {
            // Storage for topics that can be broadcast
            // or listened to
            var topics = {};
            // An topic identifier
            var subUid = -1;
            // Publish or broadcast events of interest
            // with a specific topic name and arguments
            // such as the data to pass along  
            myObject.publish = function(topic, args) {
                if (!topics[topic]) {
                    return false;
                }
                var subscribers = topics[topic],
                    len = subscribers ? subscribers.length : 0;
                while (len--) {
                    subscribers[len].func(topic, args);
                }
                return this;
            };
            // Subscribe to events of interest
            // with a specific topic name and a
            // callback function, to be executed
            // when the topic/event is observed
            myObject.subscribe = function(topic, func) {
                if (!topics[topic]) {
                    topics[topic] = [];
                }
                var token = (++subUid).toString();
                topics[topic].push({
                    token: token,
                    func: func
                });
                return token;
            };
            // Unsubscribe from a specific
            // topic, based on a tokenized reference
            // to the subscription
            myObject.unsubscribe = function(token) {
                for (var m in topics) {
                    if (topics[m]) {
                        for (var i = 0, j = topics[m].length; i < j; i++) {
                            if (topics[m][i].token === token) {
                                topics[m].splice(i, 1);
                                return token;
                            }
                        }
                    }
                }
                return this;
            };
        }(pubsub));

test demo:

        //注册事件
        var test = pubsub.subscribe("message", function(topic, data) {
            console.log("topic:" + topic + ",data:" + data);
        });
        //分布消息
        pubsub.publish("message", "siip"); //topic:message,data:test,a,b,c

        pubsub.publish("message", ["test", "a", "b", "c"]); //topic:message,data:test,a,b,c
        
        //删除注册事件
        pubsub.unsubscribe(test);

        pubsub.publish("message", {
            sender: "hello@google.com",
            body: "Hey again!"
        });

两者关系大概如下:

参考:

1、https://addyosmani.com/resour...

2、http://blog.csdn.net/cooldrag...

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/93156.html

相关文章

  • JS设计模式Obeserver(察者模式、Publish/Subscribe(发布/订阅模式

    摘要:观察者模式定义设计模式中对的定义一个对象称为维持一系列依赖于它观察者的对象,将有关状态的任何变更自动通知给它们。如图模式比较观察者模式则多了一个类似于话题调度中心的流程,发布者和订阅者解耦。 Obeserver(观察者)模式 定义 《js设计模式》中对Observer的定义:一个对象(称为subject)维持一系列依赖于它(观察者)的对象,将有关状态的任何变更自动通知给它们。 《设计模...

    荆兆峰 评论0 收藏0
  • JavaScript设计模式发布-订阅模式察者模式)-Part1

    摘要:设计模式与开发实践读书笔记。发布订阅模式又叫观察者模式,它定义了对象之间的一种一对多的依赖关系。附设计模式之发布订阅模式观察者模式数据结构和算法系列栈队列优先队列循环队列设计模式系列设计模式之策略模式 《JavaScript设计模式与开发实践》读书笔记。 发布-订阅模式又叫观察者模式,它定义了对象之间的一种一对多的依赖关系。当一个对象的状态发生改变时,所有依赖它的对象都将得到通知。 例...

    muzhuyu 评论0 收藏0
  • JavaScript设计模式发布-订阅模式察者模式)-Part2

    摘要:设计模式与开发实践读书笔记。看此文章前,建议先看设计模式之发布订阅模式观察者模式在中,已经介绍了什么是发布订阅模式,同时,也实现了发布订阅模式。 《JavaScript设计模式与开发实践》读书笔记。 看此文章前,建议先看JavaScript设计模式之发布-订阅模式(观察者模式)-Part1 在Part1中,已经介绍了什么是发布-订阅模式,同时,也实现了发布-订阅模式。但是,就Part1...

    Charlie_Jade 评论0 收藏0
  • JavaScript设计模式发布-订阅模式察者模式)-Part2

    摘要:设计模式与开发实践读书笔记。看此文章前,建议先看设计模式之发布订阅模式观察者模式在中,已经介绍了什么是发布订阅模式,同时,也实现了发布订阅模式。 《JavaScript设计模式与开发实践》读书笔记。 看此文章前,建议先看JavaScript设计模式之发布-订阅模式(观察者模式)-Part1 在Part1中,已经介绍了什么是发布-订阅模式,同时,也实现了发布-订阅模式。但是,就Part1...

    chemzqm 评论0 收藏0

发表评论

0条评论

HitenDev

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<