[b]下面是JavaScript中模仿接口实现的一种方法[/b]
<script type="text/javascript">
/**name-->接口名称
* methods-->接口的方法签名
*/
var Interface = function(name, methods) {
if(arguments.length != 2) {
throw new Error("创建接口"+name+"时,传入参数个数为:" + arguments.length
+ ", 实际需要两个参数.");
}
this.name = name;
this.methods = [];
for(var i = 0, len = methods.length; i < len; i++) {
if(typeof methods[i] !== 'string') {
throw new Error("方法名称必须是String类型.");
}
this.methods.push(methods[i]);
}
};
/**校验object是否实现了指定的接口
* object-->接口的实现类
*/
Interface.ensureImplements = function(object) {
if(arguments.length < 2) {
throw new Error("ensureImplements方法验证时必须传入待验证的接口");
}
for(var i = 1, len = arguments.length; i < len; i++) {
var interface = arguments[i];
if(interface.constructor !== Interface) {
throw new Error("传入的参数类型错误,必须为Interface类型。");
}
for(var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++) {
var method = interface.methods[j];
if(!object[method] || typeof object[method] !== 'function') {
throw new Error("在实现类中没有找到" + method
+ "方法。该类必须实现" +interface.name + "接口的" + method + "方法");
}
}
}
};
//定义ResultSet接口
var ResultSet = new Interface('ResultSet', ['save','update','del']);
var SelectInterface = new Interface('SelectInterface', ['select']);
var User = function(object){
Interface.ensureImplements(object, ResultSet, SelectInterface);
this.object = object;
};
User.prototype.oop = function(){
this.object.save();
this.object.update();
this.object.del();
this.object.select();
};
/**
*定义Obj类,实现ResultSet接口的全部方法
*/
function Obj(){}
Obj.prototype = {
save : function(){
alert("Obj-->save()方法");
},
update : function(){
alert("Obj-->update()方法");
},
del : function(){
alert("Obj-->del()方法");
},
select : function(){
alert("Obj-->select()方法");
}
}
/**
*定义Obj1类,实现ResultSet接口的全部方法
*/
function Obj1(){}
Obj1.prototype = {
save : function(){
alert("Obj1-->save()方法");
},
update : function(){
alert("Obj1-->update()方法");
},
del : function(){
alert("Obj1-->del()方法");
}
}
var obj = new Obj();
var user = new User(obj);
user.oop();
obj = new Obj1();
user = new User(obj);
user.oop();
</script>