javascript設計模式--介面

來源:互聯網
上載者:User

   最近在看javascript設計模式的書籍《pro javascript design pattrens》,覺得很不錯,可以提高自己對js oo的理解,也可能協助自己更好的理解別人寫的js library,提高自己js的水平。
        這本書中第一個重要的內容就是介面。
        大家對介面應該都不陌生,簡單的說介面就是一個契約或者規範。在強型別的面相對象語言中,介面可以很容易的實現。但是在javascript中並沒有原生的建立或者實現介面的方式,或者判定一個類型是否實現了某個介面,我們只能利用js的靈活性的特點,類比介面。
 
        在javascript中實現介面有三種方式:注釋描述、屬性驗證、鴨子模型。
note:因為我看的是英文書,翻譯水平有限,不知道有些詞彙如何翻譯,大家只能領會精神了。
 
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() {
    ...
};
 
        類比其他物件導向語言,使用interface 和 implements關鍵字,但是需要將他們注釋起來,這樣就不會有語法錯誤。
        這樣做的目的,只是為了告訴其他編程人員,這些類需要實現什麼方法,需要在編程的時候加以注意。但是沒有提供一種驗證方式,這些類是否正確實現了這些介面中的方法,這種方式就是一種文檔化的作法。
 
2. 屬性驗證(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.
}
 
        這種方式比第一種方式有所改進,介面的定義仍然以注釋的方式實現,但是添加了驗證方法,判斷一個類型是否實現了某個介面。
 
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.");
            }
        }
    }
};
 
何時使用介面?
 
        一直使用嚴格的類型驗證並不適合,因為大多數javascript程式員已經在沒有介面和介面驗證的情況下編程多年。當你用設計模式開始設計一個很複雜的系統的時候,使用介面更有益處。看起來使用介面好像限制了javascript的靈活性,但實際上他讓你的代碼變得更加的松耦合。他使你的代碼變得更加靈活,你可以傳送任何類型的變數,並且保證他有你想要的方法。有很多情境介面非常適合使用。
        在一個大型系統裡,很多程式員一起參與開發項目,介面就變得非常必要了。程式員經常要訪問一個還沒有實現的api,或者為其他程式員提供別人依賴的一個方法存根,在這種情況下,介面變得相當的有價值。他們可以文檔化api,並作為編程的契約。當存根被實現的api替換的時候你能立即知道,如果在開發過程中api有所變動,他能被另一個實現該介面的方法無縫替換。
 
如何使用介面?
 
        首先要解決的問題是,在你的代碼中是否適合使用介面。如果是小項目,使用介面會增加代碼的複雜度。所以你要確定使用介面的情況下,是否是益處大於弊端。如果要使用介面,下面有幾條建議:
        1.引用Interface 類到你的分頁檔。
        2.檢查你的代碼,確定哪些方法需要抽象到介面裡面。
        3.建立介面對象,沒個介面對象裡麵包含一組相關的方法。
        4.移除所有構造器驗證,我們將使用第三種介面實現方式,也就是鴨子類型。
        5.用Interface.ensureImplements替代構造器驗證。
作者:kbh1983

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.