3-JavaScript設計模式——commonUtils工具庫之接口類

在學習 JavaScript 設計模式之前,我們先做一個 commonUtils 工具庫,以便於後期的學習和使用。


 commonUtils 工具庫包括:多維數組遍歷,繼承函數,接口類及其驗證。


本章爲接口類

建立接口的方式:

1、註解描述法:優點  使用簡單,程序員可以有一個參考;缺點:它只是一個註釋,屬於文檔的範疇,是功能最弱的一種方式。

2、屬性檢測法:優點  比註解描述法功能強大;缺點  不能檢測接口中的方法。

3、鴨式辯型法:最完美的實現接口方式,很多大型框架底層都採用“鴨式辯型法”。


下面是 鴨式辯型法

// 命名空間
var JG = {};

// 一、接口類 完全面向對象,代碼統一,解耦
/*
  接口類需要兩個參數:
  參數1:接口的名字
  參數2:接收方法名稱的集合(數組)
*/
JG.Interface = function(name, methods){
  // 判斷接口的參數個數
  if(arguments.length != 2){
    throw new Error('this instance interface constructor arguments.length must be 2!');
  }
  
  this.name = name;
  
  // 定義一個內置空數組對象,當傳遞的參數 methods 的成員符合條件時,纔將 methods 成員(方法名字)添加到內置空數組對象 this.methods 中
  this.methods = [];
  
  for(var i = 0, len = methods.length; i < len; i++){
    if(typeof methods[i] !== 'string'){
      throw new Error('the Interface method name is error!');
    }
    this.methods.push(methods[i]);
  }
};
// 實例化接口對象
var CompositeInterface = new JG.Interface('CompositeInterface', ['add', 'remove']);

var FormItemInterface = new JG.Interface('FormItemInterface', ['update', 'select']);

// 二、準備工作,具體的實現類
var CompositeImpl = function(){
  
};

CompositeImpl.prototype.add = function(){
  alert('add...');
};

CompositeImpl.prototype.remove = function(){
  alert('remove...');
};

CompositeImpl.prototype.update = function(){
  alert('update...');
};

// CompositeImpl.prototype.select = function(){
//   alert('select...');
// };



// 三、檢驗接口裏面的方法
// 如果檢驗通過,不做任何操作;不通過:瀏覽器拋出異常error
JG.Interface.ensureImplements = function(object){
  if(arguments.length < 2){
    throw new Error('JG.Interface.ensureImplements method constructor arguments.length must be more then 2!');
  }
  // 獲得接口實例對象
    for(var i = 1, len = arguments.length; i < len; i++){
      var instanceInterface = arguments[i];
      
      // 判斷參數是否是接口類的類型
      if(instanceInterface.constructor !== JG.Interface){
        throw new Error('the ' + instanceInterface + ' is not a JG.Interface instance');
      }
      
      // 循環接口實例對象裏面的每一個方法
      for(var j = 0; j < instanceInterface.methods.length;j++){
        
        // 用一個臨時變量 接收每一個方法的名字(注意是字符串)
        var methodName = instanceInterface.methods[j];
        
        // object[key]就是方法
        if(!object[methodName] || typeof object[methodName] !== 'function'){
          throw new Error('the method "' + methodName + '" is not found...');
        }
      }
    }
};
// 實例化實現類
var c1 = new CompositeImpl();

JG.Interface.ensureImplements(c1, CompositeInterface, FormItemInterface);

結果:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章