首先我们要明白,接口其实就是强制一个类实现所有它定义的函数;这也就意味着,接口的实现其根本就在于:有效的检测实现类是否实现所有接口
我翻阅了Pro Javascript Design Pattern,其对于Javascript接口中的缺点有着深刻的理解:接口使用中的最大的问题在于,无法强迫其他程序员遵守你定义的接口
Java,c#,PHP都比较类似,如下即Java中接口的实现:
Student.java:
public interface Student {
void GetUp();
void Breakfast();
void Lunch();
void Bed();
}
StudentImpl.java:
public class StudentImpl implements Student{
public static void main(String[] args) {
StudentImpl sml = new StudentImpl();
sml.Breakfast();
}
public void GetUp() { System.out.println("起床"); }
public void Breakfast() { System.out.println("早餐"); }
public void Lunch() { System.out.println("午餐"); }
public void Bed() { System.out.println("睡觉"); }
}
可以以这种方式实现,思路为:定义一个Interface,通过检测传入的方法是否全部实现,判断接口是否实现,依寻这种方法我们可以采用如下的方式实现:
var Interface = function(className,methodsArray){
if(arguments.length!=2){
throw new Error("Error Arguments");
}
this.obj = className;
this.methods = [];
for(var i=0;i<methodsArray.length;i++){
if(typeof methodsArray[i]!=='string'){
throw new Error("methodName must be String");
}
this.methods.push(methodsArray[i]);
}
this.init();
}
Interface.prototype = {
init:function(){
if(this.obj){
for(var i=0;i<this.methods.length;i++){
var __tempMethodName__ = this.methods[i];
if(!this.obj[__tempMethodName__]){
throw new Error("please implements methods:"+__tempMethodName__);
return false;
}
}
console.log("Interface is implemented");
}
else{
throw new Error("class not found");
}
}
}
var realizeFun = new Object();
realizeFun.GetUp = function(){ console.log("起床"); }
realizeFun.Breakfast = function(){ console.log("早饭"); }
var inter = new Interface(realizeFun,['GetUp','Breakfast']);
但是我们是否会有一点别扭的感觉,怎么先定义函数&实现接口,再绑定接口呢?这样会导致接口和实现类之间的高耦合,可以改写上面的方法减小耦合:
var realizeFun = new Object();
realizeFun.GetUp = function(){ console.log("起床"); }
realizeFun.Breakfast = function(){ console.log("早饭"); }
var inter = new Interface(realizeFun,['GetUp','Breakfast']);
var Interface = function(methodsArray){
if(arguments.length!=1){
throw new Error("Error Arguments");
}
this.methods = [];
for(var i=0;i<methodsArray.length;i++){
if(typeof methodsArray[i]!=='string'){
throw new Error("methodName must be String");
}
this.methods.push(methodsArray[i]);
}
}
Interface.prototype= {
ensureImplents : function(Interimpl)
{
if(Interimpl){
for(var i=0;i<this.methods.length;i++){
var __tempMethodName__ = this.methods[i];
if(!Interimpl[__tempMethodName__]){
throw new Error("please implements methods:"+__tempMethodName__);
return false;
}
}
console.log("Interface is implemented");
}
}
}
var inter = new Interface(['GetUp','Breakfast']);
var realizeFun = {};
realizeFun.GetUp = function(){ console.log("起床"); }
realizeFun.Breakfast = function(){ console.log("早饭"); }
inter.ensureImplents(realizeFun);
参考文献: Pro Javascript Design Pattern