javascript接口實現之鴨式辨型法

//接口類
var Interface = function(name,methods){
	if(arguments.length != 2){
		throw new Error('the interface constructor arguments must be 2 length!');
	}
	this.name = name ; 
	//確保methods裏的元素爲string類型
	this.methods = [] ;
	for(var i = 0,len = methods.length ; i <len ; i++){
		 if( typeof methods[i] !== 'string'){
		 		throw new Error('the interface\'methods name must be a string type!');
		 }
		 this.methods.push(methods[i]);
	}
}

// 檢測對象是否實現相應接口中定義的方法
// 若是檢驗經過 不作任何操做 不經過:瀏覽器拋出error
Interface.ensureImplements = function(object,implInterfaces){
	// 若是檢測方法接受的參數小於2個 參數傳遞失敗!
	if(arguments.length != 2 ){
		throw new Error('Interface.ensureImplements method constructor arguments must be  == 2!');
	}
	// 得到接口實例對象 
	for(var i = 0 , len = implInterfaces.length; i<len; i++ ){
		var instanceInterface = implInterfaces[i];
		// 判斷參數是不是接口類的類型
		if(instanceInterface.constructor !== Interface){
			throw new Error('the implmented Interface constructor not be Interface Class');
		}
		// 循環接口實例對象裏面的每個方法
		for(var j = 0 ; j < instanceInterface.methods.length; j++){
			// 用一個臨時變量 接受每個方法的名字(注意是字符串)
			var methodName = instanceInterface.methods[j];
			// object[key] 就是方法
			if( !object[methodName] || typeof object[methodName] !== 'function' ){
				throw new Error("the method name '" + methodName + "' is not found !");
			}
		}
	}
}


// 二: 準備工做:
// 1 實例化接口對象
var CompositeInterface = new Interface('CompositeInterface' , ['add' , 'remove']);
var FormItemInterface  = new Interface('FormItemInterface' , ['update','select']);

// 2 具體的實現類 
var CompositeImpl = function(){
	//構造時即檢測
	Interface.ensureImplements(this,CompositeImpl.prototype.implInterfaces);
} 

//定義要實現的接口
CompositeImpl.prototype.implInterfaces = [CompositeInterface,FormItemInterface];

// 3 實現接口的方法implements methods 			
CompositeImpl.prototype.add = function(obj){
	alert('add');
	// do something ...
}
CompositeImpl.prototype.remove = function(obj){
	alert('remove');
	// do something ...
}			
CompositeImpl.prototype.update = function(obj){
	alert('update');
	// do something ...
}		
CompositeImpl.prototype.select = function(obj){
	alert('select');
	// do something ...
}

var c1 = new CompositeImpl();
c1.add();
相關文章
相關標籤/搜索