JS設計模式之介面

來源:互聯網
上載者:User

標籤:

JS能把類模仿得惟妙惟肖,也可以模仿介面,參考pro javascript design pattern一書,主要有3種方式

注釋(Comment)

這種不用多說了,就是在注釋裡寫明介面定義了哪些方法,哪些地方需要實現什麼介面。好處是不會增加任何多的對象或函數,也不會影響執行效率。壞處也很明顯,一切靠自覺,而且沒有錯誤提示。

 

屬性檢查(Attribute Checking)

function Dog() {    this.implementInterfaces = [‘Animal‘];}function play(dog) {    implement(dog, ‘Animal‘);    dog.eat();    dog.run();}function implement(obj) {    var interfaceName, interfaceFound, i, j, len;    for (i = 1; i < arguments.length; i += 1) {        interfaceName = arguments[i];        interfaceFound = false;        for (j = 0, len = obj.implementInterfaces.length; j < len; j += 1) {            if (interfaceName == obj.implementInterfaces[j]) {                interfaceFound = true;                break;            }        }        if (!interfaceFound) {            throw new Error(interfaceName + " was not implemented");        }    }}

這種方式的好處是有錯誤提示,但是仍然要靠自覺,即使檢查通過了,也不能確保就真的實現了介面的方法。

 

Duck Typing

function Interface(name, methods) {    var i, len;    if (arguments.length !== 2) {        throw new Error("exactly 2 arguments are expected");    }    this.name = name;    this.methods = [];    for (i = 0, len = methods.length; i < len; i += 1) {        if (typeof methods[i] !== ‘string‘) {            throw new Error("method name is expected to be passed in as a string");        }        this.methods.push(methods[i]);    }}Interface.ensureImplements = function (obj) {    var i, j, interface, method, l,        len = arguments.length;    if (len < 2) {        throw new Error("at least 2 arguments are expected");    }    for (i = 1; i < len; i += 1) {        interface = arguments[i];        if (interface.constructor !== Interface) {            throw new Error("instances of Interface are expected");        }        for (j = 0, l = interface.methods.length; j < l; j += 1) {            method = interface.methods[j];            if (typeof obj[method] !== ‘function‘) {                throw new Error("Method " + method + "() of Interface " + interface.name + " was not found");            }        }    }};var Animal = new Interface(‘Animal‘, [‘eat‘, ‘run‘]),
dog = new Dog();Interface.ensureImplements(dog
, Animal);

"If it walks like a duck and quacks like a duck, it‘s a duck",這個方法不去管類有沒有實現介面,而是把注意力放在執行個體上,畢竟介面裡的方法最後都要落在執行個體上,只要確保執行個體含有同名方法,就認為它實現了介面,這也是duck type命名的由來。

 

介面的實現並不複雜,重要的是恰當的判斷是否需要使用介面。

 

JS設計模式之介面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.