您的位置:首页 > Web前端 > JavaScript

Javascript笔记之 设计模式读书笔记

2014-12-10 11:16 405 查看
1.只有函数具有作用域,且作用哉是词法性质的

2.设计API该着重考虑使用它的是哪些人,会在什么情况下使用,如可使用。

3.Interface类

var Interface = function(name,methods){

    if(arguments.length !=2){

        throw new Error("Interface constructor called with "+arguments.length+"arguments,but expected exactly 2.");

    }

    this.name = name;

    this.methods = [];

    for(var i = 0,len = methods.length;i<len;i++){

        if(typeof methods[i] !== "string"){

            throw new Error("Interface constrctor expects method names to be passed in as a string.");

        }

        this.methods.push(methods[i]);

    }

};

Interface.ensureImplements = function(object){

    if(arguments.length < 2){

        throw new Error("Arguments at least 2.");

    }

    for(var i = 1,len = arguments.length;i<len;i++){

        var interface = arguments[i];

        if(interface.constructor !==Interface){

            throw new Error("Interface arguments must be instance of Interface.");

        }

        for(var j =0,mlen = interface.methods.length;j<mlen;j++){

            var m = interface.methods[j];

            if(!object[m] || typeof object[m] !== "function"){

                throw new Error("Object "+object +" does not implements "+interface.name+"."+m);

            }

        }

    }

};

4.extend函数

function extend(subClass,superClass){

    var f = function(){};

    f.prototype = superClass.prototype;

    subClass.prototype = new f();

    subClass.prototype.constructor = subClass;

    subClass.superClass = superClass.prototype;

    if(superClass.prototype.constructor == Object.prototype.constructor){

        superClass.prototype.constructor = superClass;

    }

}

5.clone函数

function clone(object){

    function f(){};

    f.prototype = object;

    return new f();

}

6.mixin函数

function mixin(recevingClass,givingClass){

    for(methodName in givingClass.prototype){

        if(!receivingClass.prototype[methodName]){

            receivingClass.prototype[methodName] = givingClass.prototype[methodName];

        }

    }

}

7.prototype属性就是用来指向原型对象的,通过原型链接机制,它提供了到所有继承而来的成员的链接。

8.工厂模式的主要好处在于消除对象间的耦合。可以把所有实例化代码集中在一个位置,这可以大大简化更换所用的类或在运行欺凌类的工作。在派生子类时它也提供了更大的灵活性。

9.适配器是一种包装器,用来对接口做适配以便在不兼容系统中使用它,用来使接口和实现分别进化;门面则是图个方便,它并不用于达到与需要特定接口的客户系统打交道这个目的,而是用于提供一个简化的接口。判断是否应该应用门面模式的关键在于辩论那些反复成组出现的代码。

10.组合对象通常拥有大量叶对象,它还保存着许多可作为外在数据处理的数据。叶对象通常只包含极少的内在数据,所以很容易被转化为共享资源。因此组合与享元模式可以完善配合。

11.

享元模式的适用场合:

网页中必须使用了大量资源密集型对象,这些对象中所保存的数据至少有一部分能被转化为外在数据,将外在数据分享出去后,独一无二的对象的数目较少。

实现享元的一般步骤:

将所有外在数据从目标类剥离,创建一个用来控制该类的实例化的工厂,创建一个用来保存外在数据的管理器。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息