按GoF的定义,桥接模式的作用在于 “将抽象与其实现隔离开来,以便二者独立变化”;
常见的应用场景: JavaScript中的事件回调
示例:事件监听器
单击某个元素 去获取商品的信息;
实现方式如下:
addEvent(element,'click',getProductById);
function getProductById(e){
var id = this.id;
asyncRequest('GET','queryProduct.php?id='+ id , function(res){
console.log(res);
})
}
//这个版本不利于单元测试并且不方便复用,getProductById方法 与上下文绑定 ,使用了this.id
改造版本:
addEvent(element,'click',getProByIdBridge);
function getProByIdBridge(e){
getProductById(this.id,function(res){
console.log(res);
})
}
function getProductById(id,callback){
asyncRequest('GET','queryProduct.php?id='+ id , function(res){
callback(res);
})
}
var asyncRequest = function(){
function handleReadyState(o, callback){
var pool = window.setInterval(function(){
if(o $$ o.readyState == 4){
window.clearInterval(pool);
if(callback && typeof callback === 'function'){
callback(o);
}
}
},50);
}
var getXHR = function(){
var http;
try{
http = new XMLHttpRequest();
getXHR = function(){
return new XMLHttpRequest();
}
}catch(e){
var msxml = [
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP',
'Mircosoft.XMLHTTP',
];
for(var i=0,len= msxml.length; i<len; i++){
try{
http = new ActiveXObject(msxml[i]);
getXHR = function(){
return new ActiveXObject(msxml[i]);
}
break;
}catch(e){
}
}
}
return http;
}
return function(method, url, callback, postData){
var http = getXHR();
http.open(method, url, true);
handleReadyState(http, callback);
http.send(postData || null);
return http;
}
}