#鸭式辨型实现接口
<script type="text/javascript" charset="UTF-8">
//鸭式辨型实现接口(最完美的javascript实现接口方式)
//核心:一个实现接口的主要目的,检测方法,并实现接口里的方法
//优点:完全面向对象,代码实现统一,解耦
//一、接口类 Class Interface 作用:实例化N个接口
//接口类需要2个参数
//参数1:接口的名字(string)
//参数2:接受方法名的集合(Array)
var Interface=function(name,methods){
//判断接口的参数个数
if (arguments.length != 2){
throw new Error(‘Interface constructor must be given 2 argument!‘)
}
this.name=name
//定义一个空数组,用于接收methods中的方法名称(string)
this.methods=[]
for (var i=0 ;i<methods.length;i++) {
if(typeof methods[i] !== ‘string‘){
throw new Error(‘Interface method name must be string!‘)
}
this.methods.push(methods[i])
}
}
//二、准备工作
//1、实例化接口对象
var CompositeInterface=new Interface(‘CompositeInterface‘,[‘add‘,‘remove‘])
var simpleInterface=new Interface(‘simpleInterface‘,[‘update‘,‘select‘])
//2、具体实现类
var CompositeImpl=function(){}
//3、实现接口的方法
CompositeImpl.prototype.add=function(obj){
console.log(‘add implement ...‘)
}
CompositeImpl.prototype.remove=function(obj){
console.log(‘remove implement ...‘)
}
CompositeImpl.prototype.update=function(obj){
console.log(‘update implement ...‘)
}
CompositeImpl.prototype.select=function(obj){
console.log(‘select implement ...‘)
}
//三、检验接口中的方法
//如果检验通过,不做任何操作,否则,抛出异常
//目的:检测方法是否存在,是否为function
Interface.checkImplements=function(obj){
//判断接受的参数小于2,则传递参数失败
if(arguments.length<2){
throw new Error(‘Interface checkImplements method constructor must be given more than 2 argument!‘)
//获得接口实例对象
for(var i=1;i<arguments.length;i++){
var instanceInterface=arguments[i]
//判断参数是否是接口类的类型
if(instanceInterface.constructor != Interface){
throw new Error(‘Interface checkImplement method constructor\‘ argument must be Interface Class‘ )
}
//循环接口实例对象里面的每一个方法
for(var j=0;j<instanceInterface.methods.length;j++){
//用一个临时变量接受每一个方法的名字(string)
var methodName=instanceInterface.methods[j]
//object[key]就是方法
if(!Object[methodName] || typeof Object[methodName] != ‘function‘){
throw new Error(‘method name:‘+methodName+‘ is not found!‘)
}
}
}
}
}
var c1=new CompositeImpl()
Interface.checkImplements(c1,CompositeInterface,simpleInterface)
c1.add()
</script>原文:http://f1yinsky.blog.51cto.com/12568071/1954065