JS 设计模式--接口实现

今天来讨论一下JavaScript中接口的实现.
最常用的莫过于‘鸭式辨型法实现接口’(较为完美的实现方法)
其实,类是否声明自己支持哪些接口并不重要,只要它具有这些接口中的方法就行。鸭式辨型(这个名称来自James Whitomb Riley的名言:“像鸭子一样走路并且嘎嘎叫的就是鸭子”)正是基于这样的认识。它把对象实现的方法集作作为判断它是不是某个类的实例的唯一标准。这种技术在检查一个类是否实现了某个接口时也可大显向身手。这种方法背后的观点很简单:如果对象具有与接口定义的方法同名的所有方法,那么就可以认为它实现了这个接口。你可以用一个辅助函数来确保对象具有所有必需的方法:

1.声明一个接口类
/**
*接口类的参数?几个
* 参数1:接口名
* 参数2:接收方法的集合(数组)
*/

var Interface = function(name , methods){
     var self = this;
     //判断接口的参数个数
     if (arguments.length !=2) {
          throw new Error('the instance interface constructor arguments should be 2');
     };
     self.name =name;
     //this.methods = methods;
     self.InterfaceMethods = [];
     methods.forEach(function(value,index){
          if (typeof value  !== "string"){
               throw new Error('the name of method is wrong');
          }
          self.InterfaceMethods.push(value);
     });
}

2.定义接口

var CompositeInterface = new Interface('CompositeInterface',['add','delete']);`
`var FormItemInterface = new Interface('FormItemInterface',['update','select']);

3.具体的实现类

var CompositeImpl = function(){}

实现接口的方法 implements methods
CompositeImpl.prototype.add = function(obj){
    alert("add");
}
CompositeImpl.prototype.delete = function(obj){
    alert("delete");
}      
CompositeImpl.prototype.update = function(obj){
    alert("update");
}
/*CompositeImpl.prototype.select = function(obj){
    alert("select");
}*/

4.检验接口里的方法
//如果检测通过,不做任何操作;不通过,则抛出异常。
//这个方法的目的就是 检测方法的

Interface.ensureImplements =function(object){
     //如果接受参数长度小于2 ,证明还有任何实现的接口
     if (arguments.length < 2) {
          throw new Error('The Interface has no implement class');
     };
          //获得接口的实例对象
    for (var i = 1,  len= arguments.length; i < len; i++) {
           var instanceInterface =arguments[i];
          //判断参数是否为 接口类的类型
          if (instanceInterface.constructor !==Interface) {
               throw new Error('The arguments constructor is not Interface Class');
          };
          for (var j = 0, len2 =instanceInterface.InterfaceMethods.length ; j <len2; j++ ) {
           //用一个临时变量 ,接收每个方法的名字(注意为字符串类型)
               var methodName =  instanceInterface.InterfaceMethods[j];
               //object[key] 获得方法
               if (!object[methodName] || typeof object[methodName] !== 'function')
               {
                    throw new Error('the method"'+ methodName+'"is not found');
               }
          }
     }
}

5.测试

var c1 =new CompositeImpl();
Interface.ensureImplements(c1,CompositeInterface,FormItemInterface);
c1.add();

输出结果
the method select is not found

发布了20 篇原创文章 · 获赞 14 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章