标签:
接口的实现方式
/** * 接口类 * @param {String} name 接口名称 * @param {Array} methods 接口方法数组 */ function Interface(name, methods) { //校验变量,输入参数必须为2 if (arguments.length !== 2) { throw new Error("state one interface require 2 parameters"); } this.name = name; this.methods = []; if (methods.length <= 0) { throw new Error(this.name + ": interface method must state"); } for (var i = 0; i < methods.length; i++) { if (typeof methods[i] !== "string") { throw new Error(this.name + ": " + method[i] + ": interface method must be string "); } this.methods.push(methods[i]); } } //创建一个接口 var Composite = new Interface("composite", ["add", "delete"]); //实现接口的类 function CompositeImpl() { } CompositeImpl.prototype.add = function() { console.log("add..."); }; CompositeImpl.prototype.delete = function() { console.log("delete..."); }; //申明一个实例 var c1 = new CompositeImpl(); /** * 校验方法 * @param {Object} object */ function checkClassImplementInterface(object) { if (arguments.length < 2) { throw new Error("check interface is required 2 parameters"); } var implementInterfaces = {}; for (var i = 1; i < arguments.length; i++) { implementInterface = arguments[i]; var implementInterfaceMethods = implementInterface.methods; for (var j = 0; j < implementInterfaceMethods.length; j++) { if (!object[implementInterfaceMethods[j]] || typeof object[implementInterfaceMethods[j]] !== "function") { throw new Error(implementInterface.name + "." + implementInterfaceMethods[j] + " id not method "); } } } } //检查类是否实现了全部接口 checkClassImplementInterface(c1, Composite);
标签:
原文地址:http://www.cnblogs.com/zhaojunyang/p/4973158.html