JavaScript之原生接口类设计

//接口类
        var Interface =  function(name , methods){
            if(arguments.length!=2){
                throw new Error('Arguments length is not qualified!');
            }
 
            this.name = name;//接口名称
            this.methods = []; //空数组存放方法名
 
            for (var i = 0 , length = arguments.length; i < length; i++) {
                if(typeof(methods[i]) != 'string'){
                    throw new Error("Method name\'s type must be 'string'!");
                }
                this.methods.push(methods[i]);
            }
 
            return this;
        };
 

        //公有共享方法:检测实例的接口是否均实现了 

        Interface.ensureImplements = function(object){//类对象实例
                if(arguments.length<2){
                    throw new Error("This instance doesn't implements any one interface!");
                }
 
                //获得接口对象实例
                for(var i = 1 , length = arguments.length; i < length ; i++){
                    var instanceInterface = arguments[i];
 
                    if(instanceInterface.constructor !== Interface){
                        throw new Error("This instanceInterface is not interface!");
                    }
 
                    for(var j = 0 ; j < instanceInterface.methods.length; j++){
                        var methodName = instanceInterface.methods[j];
                        if(!object[methodName] || typeof(object[methodName]) !== 'function'){
                            throw new Error("This instanceInterface doesn't exist the instanceInterface's method!");
                        }
                    }
                }
        }
 
        //测试接口对象的实例
        var CarInterface = new Interface('CarInterface',['start','run']);
posted @ 2017-07-17 14:53  千千寰宇  阅读(424)  评论(0)    收藏  举报