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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章