javascript設(shè)計(jì)模式 接口介紹
大家對(duì)接口應(yīng)該都不陌生,簡(jiǎn)單的說接口就是一個(gè)契約或者規(guī)范。在強(qiáng)類型的面相對(duì)象語言中,接口可以很容易的實(shí)現(xiàn)。但是在javascript中并沒有原生的創(chuàng)建或者實(shí)現(xiàn)接口的方式,或者判定一個(gè)類型是否實(shí)現(xiàn)了某個(gè)接口,我們只能利用js的靈活性的特點(diǎn),模擬接口。
在javascript中實(shí)現(xiàn)接口有三種方式:注釋描述、屬性驗(yàn)證、鴨子模型。
note:因?yàn)槲铱吹氖怯⑽臅?,翻譯水平有限,不知道有些詞匯如何翻譯,大家只能領(lǐng)會(huì)精神了。
1. 注釋描述 (Describing Interfaces with Comments)
例子:
/*
interface Composite {
function add(child);
function remove(child);
function getChild(index);
}
interface FormItem {
function save();
}
*/
var CompositeForm = function(id, method, action) { // implements Composite, FormItem
...
};
//Implement the Composite interface.
CompositeForm.prototype.add = function(child) {
...
};
CompositeForm.prototype.remove = function(child) {
...
};
CompositeForm.prototype.getChild = function(index) {
...
};
// Implement the FormItem interface.
CompositeForm.prototype.save = function() {
...
};
模擬其他面向?qū)ο笳Z言,使用interface 和 implements關(guān)鍵字,但是需要將他們注釋起來,這樣就不會(huì)有語法錯(cuò)誤。
這樣做的目的,只是為了告訴其他編程人員,這些類需要實(shí)現(xiàn)什么方法,需要在編程的時(shí)候加以注意。但是沒有提供一種驗(yàn)證方式,這些類是否正確實(shí)現(xiàn)了這些接口中的方法,這種方式就是一種文檔化的作法。
2. 屬性驗(yàn)證(Emulating Interfaces with Attribute Checking)
例子:
/* interface
Composite {
function add(child);
function remove(child);
function getChild(index);
}
interface FormItem {
function save();
}
*/
var CompositeForm = function(id, method, action) {
this.implementsInterfaces = ['Composite', 'FormItem'];
...
};
...
function addForm(formInstance) {
if(!implements(formInstance, 'Composite', 'FormItem')) {
throw new Error("Object does not implement a required interface.");
}
...
}
// The implements function, which checks to see if an object declares that it
// implements the required interfaces.
function implements(object) {
for(var i = 1; i < arguments.length; i++) {
// Looping through all arguments
// after the first one.
var interfaceName = arguments[i];
var interfaceFound = false;
for(var j = 0; j < object.implementsInterfaces.length; j++) {
if(object.implementsInterfaces[j] == interfaceName) {
interfaceFound = true;
break;
}
}
if(!interfaceFound) {
return false;
// An interface was not found.
}
}
return true;
// All interfaces were found.
}
這種方式比第一種方式有所改進(jìn),接口的定義仍然以注釋的方式實(shí)現(xiàn),但是添加了驗(yàn)證方法,判斷一個(gè)類型是否實(shí)現(xiàn)了某個(gè)接口。
3.鴨子類型(Emulating Interfaces with Duck Typing)
// Interfaces.
var Composite = new Interface('Composite', ['add', 'remove', 'getChild']);
var FormItem = new Interface('FormItem', ['save']);
// CompositeForm class
var CompositeForm = function(id, method, action) {
...
};
...
function addForm(formInstance) {
ensureImplements(formInstance, Composite, FormItem);
// This function will throw an error if a required method is not implemented.
...
}
// Constructor.
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, len = methods.length; i < len; 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]);
}
};
// Static class method.
Interface.ensureImplements = function(object) {
if(arguments.length < 2) {
throw new Error("Function Interface.ensureImplements called with "
+arguments.length + "arguments, but expected at least 2.");
}
for(var i = 1, len = arguments.length; i < len; i++) {
var interface = arguments[i];
if(interface.constructor !== Interface) {
throw new Error("Function Interface.ensureImplements expects arguments"
+ "two and above to be instances of Interface.");
}
for(var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++) {
var method = interface.methods[j];
if(!object[method] || typeof object[method] !== 'function') {
throw new Error("Function Interface.ensureImplements: object "
+ "does not implement the " + interface.name + " interface. Method " + method + " was not found.");
}
}
}
};
何時(shí)使用接口?
一直使用嚴(yán)格的類型驗(yàn)證并不適合,因?yàn)榇蠖鄶?shù)javascript程序員已經(jīng)在沒有接口和接口驗(yàn)證的情況下編程多年。當(dāng)你用設(shè)計(jì)模式開始設(shè)計(jì)一個(gè)很復(fù)雜的系統(tǒng)的時(shí)候,使用接口更有益處??雌饋硎褂媒涌诤孟裣拗屏薺avascript的靈活性,但實(shí)際上他讓你的代碼變得更加的松耦合。他使你的代碼變得更加靈活,你可以傳送任何類型的變量,并且保證他有你想要的方法。有很多場(chǎng)景接口非常適合使用。
在一個(gè)大型系統(tǒng)里,很多程序員一起參與開發(fā)項(xiàng)目,接口就變得非常必要了。程序員經(jīng)常要訪問一個(gè)還沒有實(shí)現(xiàn)的api,或者為其他程序員提供別人依賴的一個(gè)方法存根,在這種情況下,接口變得相當(dāng)?shù)挠袃r(jià)值。他們可以文檔化api,并作為編程的契約。當(dāng)存根被實(shí)現(xiàn)的api替換的時(shí)候你能立即知道,如果在開發(fā)過程中api有所變動(dòng),他能被另一個(gè)實(shí)現(xiàn)該接口的方法無縫替換。
如何使用接口?
首先要解決的問題是,在你的代碼中是否適合使用接口。如果是小項(xiàng)目,使用接口會(huì)增加代碼的復(fù)雜度。所以你要確定使用接口的情況下,是否是益處大于弊端。如果要使用接口,下面有幾條建議:
1.引用Interface 類到你的頁面文件。interface的源文件你可以再如下站點(diǎn)找到: http://jsdesignpatterns.com/.
2.檢查你的代碼,確定哪些方法需要抽象到接口里面。
3.創(chuàng)建接口對(duì)象,沒個(gè)接口對(duì)象里面包含一組相關(guān)的方法。
4.移除所有構(gòu)造器驗(yàn)證,我們將使用第三種接口實(shí)現(xiàn)方式,也就是鴨子類型。
5.用Interface.ensureImplements替代構(gòu)造器驗(yàn)證。
相關(guān)文章
一文帶你快速學(xué)會(huì)JavaScript條件判斷及高級(jí)用法
JavaScript支持其用于執(zhí)行根據(jù)不同的條件不同的操作條件語句,下面這篇文章主要給大家介紹了關(guān)于如何在JavaScript中更好的使用條件判斷的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09javascript實(shí)現(xiàn)復(fù)選框選中屬性
本文給大家介紹的是一篇國外網(wǎng)友寫的博客,講解的是關(guān)于實(shí)現(xiàn)復(fù)選框選中屬性的問題,感覺非常不錯(cuò),翻譯過來推薦給大家,希望小伙伴們能夠喜歡。2015-03-03JavaScript+HTML5 canvas實(shí)現(xiàn)放大鏡效果完整示例
這篇文章主要介紹了JavaScript+HTML5 canvas實(shí)現(xiàn)放大鏡效果,結(jié)合完整實(shí)例形式分析了javascript+HTML5 canvas針對(duì)圖片元素的獲取、響應(yīng)鼠標(biāo)事件變換元素屬性相關(guān)操作技巧,需要的朋友可以參考下2019-05-05javascript幀動(dòng)畫(實(shí)例講解)
下面小編就為大家?guī)硪黄猨avascript幀動(dòng)畫(實(shí)例講解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09js實(shí)現(xiàn)多個(gè)倒計(jì)時(shí)并行 js拼團(tuán)倒計(jì)時(shí)
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)多個(gè)倒計(jì)時(shí)并行功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02JavaScript簡(jiǎn)單編程實(shí)例學(xué)習(xí)
在本篇文章里小編給大家整理的是關(guān)于JavaScript簡(jiǎn)單編程實(shí)例學(xué)習(xí)內(nèi)容,有興趣的朋友們可以參考下。2020-02-02JavaScript原生對(duì)象之String對(duì)象的屬性和方法詳解
這篇文章主要介紹了JavaScript原生對(duì)象之String對(duì)象的屬性和方法詳解,本文講解了length、charAt()、charCodeAt()、concat()、indexOf()、lastIndexOf()等方法屬性,需要的朋友可以參考下2015-03-03如何用threejs實(shí)現(xiàn)實(shí)時(shí)多邊形折射
這篇文章主要介紹了如何用threejs實(shí)現(xiàn)實(shí)時(shí)多邊形折射,對(duì)three.js庫感興趣的同學(xué),可以參考下2021-05-05