《javascript设计模式》--接口

关于javascript设计模式书中的接口,记录如下

//TODO  增加了一个判断条件,可以只在生产环境中调用

接口var Interface = function(name,methods){
if(arguments.length != 2){
throw new Error('Interface constructor call with' + arguments.length + 'arguments,but expecter 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('Imterface constructor expects method names as to be passed in as a string.')
}
this.methods.push(methods[i]);
}
};
//static class method
Interface.ensureImplements = function(obj){
if(arguments.length < 2){
throw new Error('Function Interface.ensureImplements called with'+arguments.length +'arguments,but expected at least 2');
}
for(var i = 1, len = arguments.length; i < len; i++){
var interface = arguments[i];
if(interface.constructor !== Interface){
throw new Error('Function Interface.ensureImplements expects arguments two and above to be instances of Interface.')
}
for(var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++){
var method = interface.methods[j];
if(!obj[method] || typeof obj[method] !== 'function'){
throw new Error('Function Interface.ensureImplements: obj does\'s implement the '+ interface.name + ' interface.Method '+method +' was\'s found')
}
}
}
//TODO pass
return true;
};

用法如下:

接口//TODO define Interface
var Composite = new Interface('Composite',['add','remove','getChild']);
var FormItem = new Interface('FormItem',['save']); //TODO checkout implements
function addForm(formInstace,isDevelop){
isDevelop && Interface.ensureImplements(formInstace, Composite, FormItem)
//其他使用add,remove,getchild,save函数的代码段
}
//CompositeForm class
var CompositeForm = function(id, method, action){};
CompositeForm.prototype = {
add: function(){},
remove:function(){},
getChild:function(){}
,save:function(){}
}; var testCompositeForm = new CompositeForm()
addForm(testCompositeForm,true)

《javascript设计模式》--接口《javascript设计模式》--接口
 1 //TODO define Interface
 2 var Composite = new Interface('Composite',['add','remove','getChild']);
 3 var FormItem = new Interface('FormItem',['save']);
 4 
 5 //TODO  checkout implements
 6 function addForm(formInstace,isDevelop){
 7   isDevelop && Interface.ensureImplements(formInstace, Composite, FormItem)
 8   //其他使用add,remove,getchild,save函数的代码段
 9 }
 //CompositeForm class
 var CompositeForm = function(id, method, action){};
 CompositeForm.prototype = {
   add: function(){},
   remove:function(){},
   getChild:function(){}
   ,save:function(){}
 };
 
 var testCompositeForm = new CompositeForm()
 addForm(testCompositeForm,true)

use

上一篇:linux awk命令详解,使用system来内嵌系统命令, awk合并两列


下一篇:hihocoder 后缀自动机专题