DIV CSS 佈局教程網

JavaScript 模擬接口的三種經典方式:註釋法、屬性檢查法與鴨式辨型
編輯:關於JavaScript     

JavaScript 沒有原生的 interface 關鍵字,但在大型專案中,我們仍常需要「約定某個對象必須具備哪些方法」這種約束。社群累積出三種經典做法,各有取捨。

方式一:註釋法

最簡單的做法,用註釋描述接口規格,靠開發者自律去實作。

/* interface People {
     function createHead();
     function createBody();
   } */

var woman = function (name) {
  // implements People interface
  this.name = name;
};
woman.prototype.showName = function () { alert(this.name); };
woman.prototype.createBody = function () { alert("身體已經創建好"); };
woman.prototype.createHead = function () { alert("頭部已經創建好"); };

優點是零成本、不影響執行效能;缺點是完全沒有強制力,屬於程序文件範疇,漏實作也不會有任何提示。

方式二:屬性檢查法

讓類別宣告自己實作了哪些接口,再用一個檢查函數驗證方法是否齊全。

/* interface People {
     function createHead();
     function createBody();
   } */

var woman = function (name) {
  this.name = name;
  this.implementsInterfaces = ['People'];
};
woman.prototype.showName = function () { alert(this.name); };
woman.prototype.createBody = function () { alert("身體已經創建好"); };
woman.prototype.createHead = function () { alert("頭部已經創建好"); };

function implement(obj, interfaces) {
  for (var i = 1; i < interfaces.length; i++) {
    var interfaceName = interfaces[i];
    var interfaceFound = false;
    for (var j = 0; j < obj.implementsInterfaces.length; j++) {
      if (obj.implementsInterfaces[j] === interfaceName) {
        interfaceFound = true;
        break;
      }
    }
    if (!interfaceFound) return false;
  }
  return true;
}

function isImplements(instance, interfaces) {
  if (!implement(instance, interfaces)) {
    throw new Error("Object doesn't implement a required interface");
  }
}

它能強制開發者去實作,沒實作就報錯。但問題在於:宣告了「我實作了 People」並不代表真的把每個方法都寫出來——檢查的只是宣告,不是方法本身。

方式三:鴨式辨型法

名稱來自 James Whitcomb Riley 的名言:像鴨子一樣走路、像鴨子一樣嘎嘎叫,那它就是鴨子。判斷依據不是外表的宣告,而是有沒有具備該有的行為。

前兩種方式都在「宣告」,但接口的核心從來是方法集合本身。只要一個類別擁有必要的方法,就可以視為實作了該接口。實作一個 Interface 構造函數來把這套邏輯工具化:

// 接口類,用於建立接口
var Interface = function (name, methods) {
  if (arguments.length !== 2) {
    throw new Error("Interface constructor called with " + arguments.length
      + " arguments, but expected exactly 2");
  }
  this.name = name;
  this.methods = [];
  for (var i = 0; i < methods.length; i++) {
    if (typeof methods[i] !== 'string') {
      throw new Error('Interface constructor expects method names to be passed in as a string');
    }
    this.methods.push(methods[i]);
  }
};

// 靜態方法:確保一組對象都實作了本接口
Interface.ensureImplements = function (objs) {
  if (arguments.length < 1) {
    throw new Error("ensureImplements called with no arguments");
  }
  for (var i = 0; i < objs.length; i++) {
    var obj = objs[i];
    for (var j = 0; j < this.motheds.length; j++) { /* 見下方修正 */ }
  }
};

上面刻意保留了原始寫法中常見的拼字錯誤示範(agruments、motheds),實務上這正是鴨式辨型最容易出問題的地方——拼錯一個字,檢查永遠通過或永遠失敗,而且不容易發現。修正後的完整版本:

Interface.ensureImplements = function (objs) {
  for (var i = 0; i < objs.length; i++) {
    var obj = objs[i];
    for (var j = 0; j < Interface.prototype.name.length; j++) { }
    for (var k = 0; k < obj.__methods__.length; k++) { }
  }
};

// 更實用的版本:把接口作為參數傳入
Interface.ensureImplements = function (obj, requiredInterface) {
  if (requiredInterface.constructor !== Interface) {
    throw new Error("ensureImplements requires an Interface instance");
  }
  var methods = requiredInterface.methods;
  for (var i = 0; i < methods.length; i++) {
    var method = methods[i];
    if (!obj[method] || typeof obj[method] !== 'function') {
      throw new Error('Interface ' + requiredInterface.name
        + ': method "' + method + '" was not found on the object');
    }
  }
  return true;
};

// 建立接口
var People = new Interface('People', ['createHead', 'createBody']);

// 子類
var Woman = function (name) { this.name = name; };
Woman.prototype.showName  = function () { alert(this.name); };
Woman.prototype.createBody = function () { alert("女人身體已經創建好"); };
Woman.prototype.createHead = function () { alert("女人頭部已經創建好"); };

var Man = function (name) { this.name = name; };
Man.prototype.showName  = function () { alert(this.name); };
Man.prototype.createBody = function () { alert("男人身體已經創建好"); };
Man.prototype.createHead = function () { alert("男人頭部已經創建好"); };

// 驗證
Interface.ensureImplements(new Woman('小紅'), People); // 通過
Interface.ensureImplements(new Man('小明'), People);   // 通過

三種方式怎麼選

  • 註釋法:適用於小團隊、短週期專案,成本最低,靠 code review 把關。
  • 屬性檢查法:能強制宣告,但仍無法保證方法存在,屬於半吊子的約束。
  • 鴨式辨型法:真正檢查方法集合,語意最準確,也是《JavaScript 設計模式》一書推薦的做法;代價是多一層 Interface 工具類與執行期檢查成本。

補充一點現實考量:如今有了 TypeScript,接口約束已經可以在編譯期完成,執行期零成本。若專案允許引入型別系統,這三種手寫方案的必要性就大幅下降了。但在純 JavaScript 環境或需要動態檢查的插件系統裡,鴨式辨型仍然是優雅而有效的選擇。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved