JavaScript設計模式之一Interface接口


什么是接口?

接口提供了一種用以說明一個對象應該具有哪些方法和手段。

在面向對象的javascript中,接口有些什么作用呢?既定的一批接口具有自我描述性,並能促進代碼重用。接口可以告訴程序員一個類實現了哪些方法,從而幫助其使用這個類。

在C#還是JAVA中都應該面向接口設計我們的程序,在C#和Java中都Interface這樣的關鍵字,但是JavaScript中沒有相應的機制,但是Javascript很靈活,我們可以用它的特性去模仿Interface。

 

使用 Interface.js

var Interface = function(name, methods) {
    if(arguments.length != 2) {
        throw new Error("請確認要檢查的接口所傳的參數是否正確,例如:var Person = new Interface('Person', ['GetName','GetAge']);");
    }
    if(methods.length == 0){
        throw new Error("要檢查的接口的方法名不能為空");
    }
    this.Name = name;
    this.Method = [];
    for(var i = 0; i < methods.length; i++) {
        if(typeof methods[i] !== 'string') {
            throw new Error("方法名不是字符串");
        }
        this.Method.push(methods[i]);
    }
}
/*static method in interface*/
Interface.ensureImplement = function(object) {
    if(arguments.length < 2) {
        throw new Error("沒有接口或實例");
    }

    for(var i = 1; i < arguments.length; i++) {
        var interface1 = arguments[i];
        if(interface1.constructor !== Interface) {
            throw new Error("參數不是接口");
        }
        for(var j = 0; j < interface1.Method.length; j++) {
            var method = interface1.Method[j];
            if(!object[method] || typeof object[method] !== 'function') {
                throw new Error("您的實例沒有實現接口:\t" + method);
            }
        }
    }
}

 

案例:

// 封裝接口的類,假如該類中實現的  add del 2個方法
function Peson(){}
Peson.prototype.add = function(){
    console.log('新增接口');
}
Peson.prototype.del = function(){
    console.log('刪除接口');
}

//在你使用該類的方法的時候先去檢查你要用到的方法是否存在
var peson = new Peson();
//Interfaces
var check = new Interface('check',['add', 'del']);
//檢查你要用到的方法是否存在,如果你要用的方法沒有實現,會拋出錯誤提示
Interface.ensureImplement(peson, check);
//使用接口
peson.add();
peson.del();

使用es6 的class 也是可以的

class Peson{
    add(){
        console.log('新增接口');
    }
    del(){
        console.log('刪除接口');
    }
}
//在你使用該類的方法的時候先去檢查你要用到的方法是否存在
var peson = new Peson();
//Interfaces
var check = new Interface('check',['add', 'del']);
//檢查你要用到的方法是否存在,如果你要用的方法沒有實現,會拋出錯誤提示
Interface.ensureImplement(peson, check);
//使用接口
peson.add();
peson.del();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM