1.鸭式辨型的核心监测接口里的方法是否被实现类都实现
<script type="application/javascript">
/**
* 定义接口类
* @param name 接口名称
* @param methods 方法数组
* @constructor
*/
var Interface = function (name, methods) {
if (arguments.length != 2) {
return;
}
this.name = name;
this.methods = [];
for (var i = 0, len = methods.length; i < len; i++) {
if (typeof methods[i] != 'string') {
return;
}
this.methods.push(methods[i]);
}
};
/**
* 实现类
*/
var MyInterfaceImpl = function () {
};
MyInterfaceImpl.prototype.setName = function (name) {
this.name = name;
console.log(name);
};
MyInterfaceImpl.prototype.getName = function () {
console.log(this.name);
};
/**
* 检测接口里面的方法
* @param obj
*/
Interface.ensureImplements = function (obj) {
if (arguments.length < 2) {
throw new Error('最少传递两个参数');
}
// 获取接口实现方法
for (var i = 1; i < arguments.length; i++) {
var instanceInterface = arguments[i];
if (instanceInterface.constructor != Interface) {
return;
}
// 循环接口的每个方法
for (var j = 0, len = instanceInterface.methods.length; j < len; j++) {
var methodName = instanceInterface.methods[j];
if (!obj[methodName] || typeof obj[methodName] != 'function') {
return;
}
}
}
};
var c1 = new MyInterfaceImpl('MyInterfaceImpl', ['setName', 'getName']);
c1.setName('测试');
c1.getName();
</script>