<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
// 鴨式辨型法實現的核心:一個類實現接口的主要目的:把接口裏的方法都實現(檢測方法)
// 一: 接口類 Class Interface ==>實例化N多個接口
/**
* 接口類需要2個參數
* 參數1: 接口的名字 (string)
* 參數2: 接受方法名稱的集合(數組) (array)
*/
var Interface = function(name , methods){
//判斷接口的參數個數
if(arguments.length != 2){
throw new Error('argument.length must be 2');
}
this.name = name;
this.methods = [];//定義一個內置的空數組對象 等待接受methods裏的元素(方法名字)
for(var i = 0, len = methods.length ;i < len; i++ ){
if(typeof methods[i] != 'string'){
throw new Error('methods.type must be string');
}
this.methods.push(methods[i]);
}
}
// 二: 準備工作:
// 1 實例化接口對象
var CompositeInterface = new Interface('CompositeInterface' , ['add' , 'remove']);
var FormItemInterface = new Interface('FormItemInterface' , ['update','select']);
// CompositeImpl implements CompositeInterface , FormItemInterface
// 2 具體的實現類
var CompositeImpl = function(){
}
// 3 實現接口的方法implements methods
CompositeImpl.prototype.add = function(){
alert('add...');
}
CompositeImpl.prototype.update = function(){
alert('update...');
}
CompositeImpl.prototype.select = function(){
alert('select...');
}
CompositeImpl.prototype.remove = function(){
alert('remove...');
}
// 三:檢驗接口裏的方法
// 如果檢驗通過 不做任何操作 不通過:瀏覽器拋出error
// 這個方法的目的 就是檢測方法的
Interface.ensureImplements = function(object){
// 如果檢測方法接受的參數小於2個 參數傳遞失敗!
if(arguments.length < 2){
throw new Error('Interface.ensureImplements method constructor arguments must be >= 2!');
}
// 獲得接口實例對象
for(var i = 1; i < arguments.length;i++){
var instanceInterface = arguments[i];
if(instanceInterface.constructor != Interface){
throw new Error('the arguments 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 !");
}
}
}
}
var c1 = new CompositeImpl();
Interface.ensureImplements(c1,CompositeInterface,FormItemInterface);
c1.add();
</script>
</body>
</html>
js接口鴨式辨型法實現
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.