javascript接口实现之鸭式辨型法

来源:互联网 发布:黑客网站软件免费下载 编辑:程序博客网 时间:2024/05/13 03:08
//接口类var Interface = function(name,methods){if(arguments.length != 2){throw new Error('the interface constructor arguments must be 2 length!');}this.name = name ; //确保methods里的元素为string类型this.methods = [] ;for(var i = 0,len = methods.length ; i <len ; i++){ if( typeof methods[i] !== 'string'){ throw new Error('the interface\'methods name must be a string type!'); } this.methods.push(methods[i]);}}// 检测对象是否实现相应接口中定义的方法// 如果检验通过 不做任何操作 不通过:浏览器抛出errorInterface.ensureImplements = function(object,implInterfaces){// 如果检测方法接受的参数小于2个 参数传递失败!if(arguments.length != 2 ){throw new Error('Interface.ensureImplements method constructor arguments must be  == 2!');}// 获得接口实例对象 for(var i = 0 , len = implInterfaces.length; i<len; i++ ){var instanceInterface = implInterfaces[i];// 判断参数是否是接口类的类型if(instanceInterface.constructor !== Interface){throw new Error('the implmented Interface constructor not be Interface Class');}// 循环接口实例对象里面的每一个方法for(var j = 0 ; j < instanceInterface.methods.length; j++){// 用一个临时变量 接受每一个方法的名字(注意是字符串)var methodName = instanceInterface.methods[j];// object[key] 就是方法if( !object[methodName] || typeof object[methodName] !== 'function' ){throw new Error("the method name '" + methodName + "' is not found !");}}}}// 二: 准备工作:// 1 实例化接口对象var CompositeInterface = new Interface('CompositeInterface' , ['add' , 'remove']);var FormItemInterface  = new Interface('FormItemInterface' , ['update','select']);// 2 具体的实现类 var CompositeImpl = function(){//构造时即检测Interface.ensureImplements(this,CompositeImpl.prototype.implInterfaces);} // 3 定义要实现的接口CompositeImpl.prototype.implInterfaces = [CompositeInterface,FormItemInterface];// 4 实现接口的方法implements methods CompositeImpl.prototype.add = function(obj){alert('add');// do something ...}CompositeImpl.prototype.remove = function(obj){alert('remove');// do something ...}CompositeImpl.prototype.update = function(obj){alert('update');// do something ...}CompositeImpl.prototype.select = function(obj){alert('select');// do something ...}var c1 = new CompositeImpl();c1.add();

0 0
原创粉丝点击