JS设计模式——装饰者模式

var Interface = function(name, methods) {
    if (arguments.length != 2) {
        throw new Error('2个参数需要');
    }
    this.name = name;
    this.methods = [];
    for (var i = 0; i < methods.length; i++) {
        if (typeof methods[i] !== 'string') {
            throw new Error('方法名称应该是字符串');
        }
        this.methods.push(methods[i]);
    }
}

Interface.ensureImplements = function(object) {
    if (arguments.length < 2) {
        throw new Error('arguments at lest 2');
    }
    for (var i = 1; i < arguments.length; i++) {
        var interfacetmp = arguments[i];
        if (interfacetmp.constructor !== Interface) {
            throw new Error('not Interface');
        }
        for (j = 0; j < interfacetmp.methods.length; j++) {
            var method = interfacetmp.methods[j];
            if (!object[method]  || typeof object[method] != 'function') {
                throw new Error(method + '没有实现接口方法');
            }
        }
    }
}

function extend(subClass, supClass) {
    var F = function() {};
    F.prototype = supClass.prototype;
    subClass.prototype = new F();
    subClass.prototype.constructor = subClass;
    subClass.supClass = supClass.prototype;
    if(supClass.prototype.constructor == Object.prototype.constructor){
        supClass.prototype.constructor = supClass;
    }

}
//自行车 接口
        var Bicyle = new Interface('Bicyle',['assemble','wash','ride','repair','getPrice']);
        
        //AcmeComfortCruiser 品牌的自行车
        var AcmeComfortCruiser = function(){};
        AcmeComfortCruiser.prototype = {
            assemble:function(){},
            wash:function(){},
            ride:function(){},
            repair:function(){},
            getPrice:function(){
                return 399.00;
            },
        };
        
        //自行车配件 装饰者类  它是所有配件类的超类
        /**
         * @param {type} bicyle 自行车类的 实例
         * 他是一个 抽象类
         * */
        var BicyleDecoratot = function(bicyle){
            Interface.ensureImplements(bicyle,Bicyle);
            this.bicyle = bicyle;
            this.interface = Bicyle;
            outerLoop:for(var key in this.bicyle){
                //如果 不是函数 继续循环
                if(typeof this.bicyle[key] !== 'function'){
                    continue outerLoop;
                }
                // 如果函数在 接口中 继续循环
                for(var i=0;i

你可能感兴趣的:(JS设计模式——装饰者模式)