鸭式辨型法实现JavaScript接口:
//ya shi bian li 法实现接口
//接口检验,要能够检验是否实现个接口,及接口中所有的方法
//定义接口对象
var Interface = function(interfacename,methodArray){
if(arguments.length < 2){
throw new Error('the instance of interface constructor must be 2 length');
}
this.name = interfacename;
this.methods = [];
var length = methodArray.length;
for(var i = 0 ; i < length; i ++){
if(typeof methodArray[i] != 'string'){
throw new Error('the Interface method name is error!');
}
this.methods.push(methodArray[i]);
}
}
//声明接口实例
var CompositInterface = new Interface("CompositInterface",["add","edit"]);
var FormItemInterface = new Interface("FormItemInterface",["delete","select"]);
//定义实现类,实现这两个接口
var InterfaceImp = function(){
}
InterfaceImp.prototype.add = function(){
}
InterfaceImp.prototype.edit = function(){
}
InterfaceImp.prototype.delete = function(){
}
// IntefaceImp.prototype.select = function(){
// }
//检验接口实例是否实现 接口的所有方法
Interface.ensureImplements = function(object){
if(arguments.length < 2){
throw new Error("接口检验的方法,参数不能少于2");
}
for(var i = 1; i < arguments.length; i++){
var tmpInterface = arguments[i];
for(var j = 0, length = tmpInterface.methods.length; j < length; j++){
var methodName = tmpInterface.methods[j];
if(!object[methodName] || typeof object[methodName] != 'function'){
throw new Error(object.constructor.name + "没有实现接口" + tmpInterface.name +"的方法" + methodName);
}
}
}
return true;
}
var instance = new InterfaceImp();
Interface.ensureImplements(instance,CompositInterface,FormItemInterface);
instance.add();