沒想到javascript還可以類比介面,頓時覺得js更加強大,所以把《javascript設計模式》的內容摘錄出來,供大家學習,內容稍有改動.
1.在javascript中引入介面的好處:
介面具有自我描述性,可以促進代碼的重用;有利於不同的類之間進行通訊,在大型項目中尤其有用;有利於代碼的測試和調試。
2.引入介面的弊端
介面的引入強化了類型的作用,降低了語言的靈活性;帶來額外的開銷;無法強迫其他程式員遵守你定義的介面。
3.模仿介面的方法
方法1:用注釋描述
View Code
1 /* 2 interface composite{ 3 function add(child); 4 function remove(child); 5 function getChild(index); 6 } 7 interface FormItem{ 8 function save(); 9 } 10 */11 var CompositeForm = function(){12 ...13 }14 15 CompositeForm.prototype = {16 add: function(child){...},17 remove: function(child){...},18 getChild: function(index){...},19 save: function(){...}20 }
該方法的不足:主要屬於程式文檔的範圍,對介面的遵守完全依靠自覺。
方法2:用屬性檢查類比介面
View Code
/* interface composite{ function add(child); function remove(child); function getChild(index); } interface FormItem{ function save(); } */ var CompositeForm = function(){ this.implementsInterfaces = ['Composite','FormItem']; ... } function addForm(formInstance){ if(! implements(formInstance,'Composite','FormItem')){ throw new Error('object does not omplement a required interface'); } ... } function implements(object){ for(var i=1;i<arguments.length;i++){ var interfaceName = arguments[i]; var found = false; for(var j=0;j<object.implementsInterfaces.length;j++){ if(object.implementsInterfaces[j] === interfaceName){ found = true; break; } } if(! found){ return false; //an interface was not found } } return true;}
該方法的特點是顯示地聲明自己支援什麼介面,但是並未確保類真正實現了自稱的介面。
方法3.鴨式變型類比介面
首先是Interface類的定義
View Code
1 var Interface = function(name,methods){ 2 if(arguments.length != 2){ 3 throw new Error('....'); 4 } 5 this.name = name; 6 this.methods = []; 7 for(var i=1; i< methods.lenght;i++){ 8 if(typeof method[i] !== 'string'){ 9 throw new Error(...);10 } 11 this.methods.push(methods[i]);12 }13 }14 Interface.ensureImplements = function(object){15 if(arguments.length < 2){16 throw new Error(...);17 }18 for(var i=1;i<arguments.lenght;i++){19 var interfaceName = arguments[i];20 if(interfaceName.constructor !==Interface){21 throw new Error(...);22 }23 for(var j=0; j<interfaceName.methods.length;j++){24 var method = interfaceName.methods[j];25 if(!object[method] || typeof object[method] !== 'function'){26 throw new Error(...);27 }28 }29 }30 }
接下來類比介面:
View Code
1 /* 2 interface composite{ 3 function add(child); 4 function remove(child); 5 function getChild(index); 6 } 7 interface FormItem{ 8 function save(); 9 } 10 */11 var Composite = new Interface('Composition',['add','remove','getChild']);12 var FormItem = new Interface('FormItem',['save']);13 14 var CompositeForm = function(){15 ...16 }17 18 function addForm(formInstance){19 Interface.ensureImplements(formInstance,Composite,FormItem);20 ...21 }
特點:可以保證強制實施類實現介面,但是缺少自我描述,同時還需要一個輔助類(Interface)和輔助函數(ensureImplements)。
4.結論:
類比介面最好的辦法同時使用注釋和鴨式變型方法。其實類比介面不是最難的,痛點在於何時使用介面。