Javascript 设计模式笔记

设计模式太多了 还有些模式概念非常接近(比如观察者 中介者 和 事件发布/订阅模式)

构造器模式

var newObject = {}
var newObject = new XXX();

模块模式 (函数包裹 私有变量)

保护私有变量&& 模块引出

var MODULE = (function () {
    var my = {},
        privateVariable = 1;
     
    function privateMethod() {
        // ...
    }
     
    my.moduleProperty = 1;
    my.getPrivateVariable = function () {
        // ...
    };
     
    return my;
}());

模块引入

(function ($, YAHOO) {
    // 当前域有权限访问全局jQuery($)和YAHOO
}(jQuery, YAHOO));

单例模式

var mySingle = (function(){
    var instance;
    var init = function(){
        return {
            pubFun: function(){
                //...            
            }
        }
    };
    return {
        getInstance: function(){
            if(!instance){
                instance = init();
            }
            return instance;
        }
    }
})();
var A = mySingle.getInstance()
var B = mySingle.getInstance()
A == B //true

事件发布订阅模式

    var MyEvent = {
        _listener: {},
        addEvent:function(type, fn){
            if(!this._listener[type]){
                this._listener[type] = []
            }
            this._listener[type].push(fn);

        },
        fireEvent:function(type, caller){
            if(this._listener[type]){
                this._listener[type].forEach(function(fn){
                    fn.call(caller);
                });
            }
        },
        removeEvent:function(type, fn){
            if(this._listener[type]){
                for (var i = 0, len = this._listener[type].length ; i < len; i++) {
                    this._listener[type].splice(i,1);
                };
            }
        }
    };

和观察者模式的区别
Observer模式希望观察者订阅内容改变的事件
而发布订阅模式允许自定义事件, 事件可以传递自定义参数
我理解的是观察者模式notify的时候所有的监听者都会做响应 它只发一种广播
而发布订阅模式发多种事件 对应的事件做响应

原型模式

使用Object.create(yourProtoType) 或者自己指定原型

    var car = {
        init: function(name){
            this.name = name;
        },
        drive: function(){
            console.log(this.name + ' is driving..');
        }
    }
    var yourCar = Object.create(car);
    yourCar.init('Honda');
    yourCar.drive();

OR

    var car = {
        init: function(name){
            this.name = name;
        },
        drive: function(){
            console.log(this.name + ' is driving..');
        }
    }
    function carFactory(name){
        function F(){};
        F.prototype = car;
        var f = new F();
        f.init(name);
        return f;
    }
    var yourCar = carFactory('Honda');
    yourCar.drive();

posted @ 2015-09-10 17:43  cart55free99  阅读(137)  评论(0编辑  收藏  举报