【示例】
-
JS
function Interface( name, methods ){ // 接口辅助类,参数包括接口实例的名称和方法集 if( arguments.length != 2 ){ // 如果参数个数不等于2,则抛出错误 throw new Error( "该接口实例包含" + arguments.length + "个参数, 但标准接口约定两个参数." ); } this.name = name; // 存储第一个参数值 this.methods = []; // 接口实例的方法存储器 if( methods.length < 1 ){ // 如果第二个参数元素数为0,说明是空数组,抛出异常 throw new Error( "接口实例的第二个参数是空的。" ); } for( var i = 0; i < methods.length; i ++ ){ // 遍历第二个参数的每个元素,合乎接口标准设计要求,则写入接口实例的方法存储器 this.methods if( typeof methods[i][0] !== 'string' ){ throw new Error( "接口约定的第一个参数应为字符串。" ); } if( methods[i][1] && typeof methods[i][1] !== 'number' ){ throw new Error( "接口约定的第二个参数应为数值。"); } if( methods[i].length == 1 ){ methods[i][1] = 0; } this.methods.push( methods[i] ); // 把方法写入数组存储器 } } Interface.implements = function( o ){ // 接口辅助类,检测类方法是否符合接口实例约定 if( arguments.length < 2 ){ // 检测该方法的传递参数值是否符合规定 throw new Error( "接口约定类应包含至少二个参数。" ); } for( var i = 1 ; i < arguments.length; i ++ ){ // 检测类所遵守接口实例是否合法(符合接口标准设计) var interface = arguments[i]; if( interface.constructor !== Interface ) { // 检测接口实例是否继承接口标准 throw new Error( "从第二个以上的参数必须为接口实例." ); } for( var j = 0; j < interface.methods.length; j ++ ){ // 检测类方法是否符合接口实例的约定 var method = interface.methods[j][0]; if( ! o[method] || typeof o[method] !== 'function' || o[method].length != interface.methods[j][1] ){ throw new Error( "该实现类没能履行" + interface.name + "接口方法" + method + "约定。" ); } } } } -
JS
var Get = new Interface( "Get", [["get", 0]] ); // 该标准包含方法get() var Set = new Interface( "Set", [["set", 1]] ); // 该标准包含方法set() var Saying = new Interface( "Saying", [["saying", 1]] ); // 该标准包含方法saying() var Base = new Interface( "Base", [["get", 0], ["set", 1]] ); // 该标准包含方法get()和set() var Base1 = new Interface( "Base1", [["set", 1], ["get", 0]] ); // 该标准包含方法set()和get() var Base2 = new Interface( "Base2", [["get", 0], ["set", 1] , ["saying", 1]] ); // 该标准包含三个方法 function Neddy(){ // 接口实现类 this.name = ""; Interface.implements( this, Base,Get,Set ); // 绑定应该实现的接口实例,即引用接口标准的implements()方法,并指定要遵守的 } Neddy.prototype.get = function(){ return this.name; } Neddy.prototype.set = function( name ){ this.name = name; } var neddy = new Neddy(); neddy.set( "Testing..." ); alert( neddy.get() ); // 返回字符串"Testing...",接口约定顺利通过