桥接模式定义:桥梁模式的用意是"将抽象化(Abstraction)与实现化(),使得二者可以独立地变化"。这句话有三个关键词,也就是抽象化、实现化和脱耦。
最简单的桥接模式例子:事件监听器
addEvent(element,"click",getResultByIdBridge); function getResultByIdBridge(e){ getById(this.id, function(result){ //TODO: this is operate result }); }
桥接模式复杂例子:构建XHR连接队列
1 var asyncRequest = (function(){ 2 3 function handleReadyState(o,callback){ 4 var poll = window.setInterval(function(){ 5 if(o && o.readyState ==4){ 6 window.clearInterval(poll); 7 if(callback) callback(o); 8 } 9 },50); 10 } 11 12 var getXHR = function(){ 13 var http; 14 try{ 15 http = new XMLHttpRequest(); 16 getXHR = function(){ 17 return new XMLHttpRequest(); 18 }; 19 }catch(e){ 20 var msxml = ["MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"]; 21 for(var i =0, len = msxml.length;i0){111 return ;112 }113 if(this.paused){114 this.paused = false;115 return;116 }117 118 var that = this;119 this.currentRetry++;120 var abort = function(){121 that.conn.abort();122 if(that.currentRetry == that.retryCount){123 that.onFailure.fire();124 that.currentRetry = 0;125 }else{126 that.flush();127 }128 };129 130 this.timer = window.setTimeout(abort,this.timeout);131 var callback = function(o){132 window.clearTimeout(that.timer);133 that.currentRetry = 0;134 that.queue.shift();135 that.onFlush.fire(o.responseText);136 if(that.queue.length == 0){137 that.onComplete.fire();138 return;139 }140 that.flush();141 };142 143 this.conn = asyncRequest(this.queue[0]["method"],this.queue[0]["url"],callback,this.queue[0]["params"]);144 }).145 method("setRetryCount",function(count){146 this.retryCount = count;147 }).148 method("setTimeout",function(time){149 this.timeout = time;150 }).151 method("add",function(o){152 this.queue.push(o);153 }).154 method("pause",function(){155 this.paused = true;156 }).157 method("dequeue",function(){158 this.queue.pop();159 }).160 method("clear",function(){161 this.queue = [];162 });
对应的html
1 2 3 4 56 13 14 15 1640 41 42 43Ajax Conection Queue
17 181927Add Requests to Queue
2021
26- add 01 to Queue
22- add 02 to Queue
23- add 03 to Queue
24- add 04 to Queue
25oTther Queue actions
28 34 353639Results:
37 38