《javaScript模式》--设计模式

2020-02-18  本文已影响0人  牛油果大虾

javaScript常用模式9种

迭代器模式

//例子实现
        var agg = (function () {
            var index = 0,
                data = [1, 2, 3, 4, 5],
                length = data.length;
            return {
                next: function () {
                    var element;
                    if (!this.hasNext()) {
                        return null;
                    }
                    element = data[index];
                    index = index + 2;
                    return element;
                },
                hasNext: function () {
                    return index < length
                },
                rewind: function () {
                    index = 0
                },
                current: function () {
                    return data[index]
                }
            }
        }());
        //测试迭代器
        while(agg.hasNext()) {
            console.log(agg.next());
        }
        //回退
        agg.rewind();
        console.log(agg.current());

观察者模式

var publisher = {
            subscribers: {
                any: []//事件类型:订阅者
            },
            //将订阅者添加到订阅者数组
            subscribe: function (fn, type) {
                type = type || 'any';
                if (typeof this.subscribe[type] === "undefined") {
                    this.subscribers[type] = [];
                }
                this.subscribers[type].push(fn);
                console.log(this.subscribers[type])
            },
            //移除订阅者
            unsubscribe: function (fn, type) {
                this.visitSubscribers('unsubscribe', fn, type);
            },
            publish: function (publication, type) {
                this.visitSubscribers('publish', publication, type);
            },
            visitSubscribers: function (action, arg, type) {
                var pubtype = type || 'any',
                    subscribers = this.subscribers[pubtype],
                    i,
                    max = subscribers.length;
                for (i = 0; i < max; i++) {
                    if (action = 'publish') {
                        subscribers[i](arg);
                        console.log('arg is ,' + arg)
                    } else {
                        if (subscribers[i] === arg) {
                            subscribers.splice(i, 1);
                        }
                    }
                }
            }
        }

        //makePublisher接受一个对象作为参数,通过吧上述通用发布者复制到该对象中,将其转化为一个发布者
        function makePublisher(o) {
            var i;
            for (i in publisher) {
                if (publisher.hasOwnProperty(i) && typeof publisher[i] === "function") {
                    o[i] = publisher[i];
                }
            }
            o.subscribers = { any: {} };
        }
        //paper对象用于发布日报和月刊
        var paper = {
            daily: function () {
                this.publish('big news today');
            },
            monthly: function () {
                this.publish('interesting analysis', 'monthly');
            }
        }
        //将paper构成一个发行者
        makePublisher(paper);
        //订阅者对象joe方法
        var joe = {
            drinkCoffee: function (paper) {
                console.log('just read' + paper);
            },
            sundayPreNap: function (monthly) {
                console.log('About to fall asleep reading this' + monthly);
            }
        }

        //paper注册joe
        paper.subscribe(joe.drinkCoffee);
        // paper.subscribe(joe.sundayPreNap, 'monthly');

        paper.daily();
        // paper.daily();
        // paper.daily();
        // paper.monthly();


        // makePublisher(joe);

        // joe.tweet = function (msg) {
        //     this.publish(msg);
        // };

        // paper.readTweets = function (tweet) {
        //     alert('Call big meeting! Someone ' + tweet);
        // };

        // joe.subscribe(paper.readTweets);

        // joe.tweet("hated the paper today");

总结

  1. 单体模式
    针对一个'类'创建一个对象.如果您想以构造函数的方法替换类的思想并且还保持类似java的语法,我们则为您考虑了多种方法.另外从技术上来说,javaScript中的所有对象都是单体.然而有时候程序员也会说单体,他们的本意是指以模块模式创建的对象.
  2. 工厂模式
    根据字符串指定的类型在运行时创建对象的方法
  3. 迭代器模式
    提供一个API来操纵或遍历复杂的自定义数据结构
  4. 装饰者模式
    通过从预定义的装饰者对象中添加功能,从而在运行时调整对象
  5. 策略模式
    在选择最饥饿策略以处理特定任务(上下文)的时候仍然保持相同的接口
  6. 外观模式
    把常用方法包装在一个新的API中提供新的方法
  7. 代理模式
    通过包装一个对象控制对他的访问,其主要方法是将访问聚集为组或仅当真正必要时才执行的访问,从而避免了高昂的操作开销
  8. 中介者模式
    通过使您的对象之间相互并不直接的通话,而是仅通过一个中介者对象进行通信,形成松散耦合
    9.观察者模式
    通过创建的'可观察的'对象,当发生一个感兴趣的事件时可将该事件通知给所有的观察者,从而形成松散耦合
上一篇下一篇

猜你喜欢

热点阅读