JavaScript設計模式之一Interface介面

來源:互聯網
上載者:User
如何用物件導向的思想來寫JavaScript,對於初學者應該是比較難的,我們經常用的JQuery其實也是用物件導向的思想去封裝的,今天我們來看看如何在Javascript中用Interface,在C#還是JAVA中都應該面向介面設計我們的程式,在C#和Java中都Interface這樣的關鍵字,但是JavaScript中沒有相應的機制,但是Javascript很靈活,我們可以用它的特性去模仿Interface,但是我們需要加入一些methods來做check的動作。我們來看下一個Interface的作用: 繼承了這個Interface就必須要實現這個Interface中定義的方法(方法簽名)//JavaScript 現在還做不到方法的簽名的約束
var Interface = function (name, methods) {
if (arguments.length != 2) {
throw new Error("the interface length is bigger than 2");
}
this.Name = name;
this.Method = [];
for (var i = 0; i < methods.length; i++) {
if(typeof methods[i]!== 'string') {
throw new Error("the method name is not string");
}
this.Method.push(methods[i]);
}
}
/*static method in interface*/
Interface.ensureImplement = function (object) {
if (arguments.length < 2) {
throw new Error("there is not Interface or the instance");
}

for (var i = 1; i < arguments.length; i++) {
var interface1 = arguments[i];
if (interface1.constructor !== Interface) {
throw new Error("the argument is not interface");
}
for (var j = 0; j < interface1.Method.length; j++) {
var method = interface1.Method[j];
if (!object[method] || typeof object[method] !== 'function') {
throw new Error("you instance doesn't implement the interface");

}
}
}
}
我們來分析一下code,我們現在的做法是用來比較一個Instance中的方法名在介面中是否定義了。我先定義一個介面(2個參數),第二個參數是介面中的方法名。Check方法用簡單的2層for迴圈來做比較動作。我們來看下如何去用這個介面:
 var Person = new Interface("Person", ["GetName", "GetAge"]);

var Man = function (name, age) {
this.Name = name;
this.Age = age;
}
Man.prototype = { GetName: function () { return this.Name; },
// GetAge: function () { return this.Age; }
}
var test = function (instance) {
Interface.ensureImplement(instance, Person);
var name = instance.GetName();
alert(name);

}
test(new Man("Alan",20));
如果我們注釋了上面的GetAge方法,在執行的時候就會出錯。在ensureImplement的時候發現並沒有去實現這個方法。說實話,這樣的排版確實很uglily, 大家看的時候原諒,沒這麼寫過,以後一定多寫點東西。By the way, I'm Alan_chen in MSDN forums for C# and DataPlatform(Entity Framework).如需轉寄請註明原文出處:http://www.cnblogs.com/jsjrjcj/archive/2011/05/25/2056627.html
相關文章

聯繫我們

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