您的位置:首页 > Web前端 > JavaScript

js设计模式-桥接模式

2016-04-02 19:13 381 查看
桥接模式定义:桥梁模式的用意是"将抽象化(Abstraction)与实现化(Implementation)脱耦,使得二者可以独立地变化"。这句话有三个关键词,也就是抽象化、实现化和脱耦。

最简单的桥接模式例子:事件监听器

addEvent(element,"click",getResultByIdBridge);
function getResultByIdBridge(e){
getById(this.id, function(result){
//TODO: this is operate result
});
}


桥接模式复杂例子:构建XHR连接队列

var asyncRequest = (function(){

function handleReadyState(o,callback){
var poll = window.setInterval(function(){
if(o && o.readyState ==4){
window.clearInterval(poll);
if(callback) 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","Microsoft.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();
console.log("send url is:" + url);
http.open(method,url,true);
handleReadyState(http,callback);
http.send(postData || null);
}
})();

Function.prototype.method = function(name,fn){
this.prototype[name] = fn;
return this;
}

if(!Array.prototype.forEach){
Array.method("forEach",function(fn,thisObj){
var scope = thisObj || window;
for(var i = 0, len = this.length;i<len;i++){
fn.call(scope,this[i],i,this);
}
})
}

if(!Array.prototype.filter){
Array.method("filter",function(fn,thisObj){
var scope = thisObj || window;
var a  = [];
for(var i = 0 , len = this.length;i<len;i++){
if(fn.call(scope,this[i],i,this)){
a.push(this[i]);
}
}
return a;
})
}

/******************************************/
window.DED = window.DED || {};
DED.util = DED.util || {};
DED.util.Observer = function(){
this.fns = [];
}
DED.util.Observer.prototype = {
subscribe:function(fn){ //签署
this.fns.push(fn);
},
unsubscribe:function(fn){
this.fns = this.fns.filter(function(item){
if(item != fn){
return item;
}
});
},
fire:function(o){
this.fns.forEach(function(item){
item(o);
});
}
}

DED.Queue = function(){
this.queue = [];
this.onComplete = new DED.util.Observer();
this.onFailure = new DED.util.Observer();
this.onFlush = new DED.util.Observer();

this.retryCount = 3;
this.currentRetry = 0;
this.paused = false;
this.timeout = 5000;
this.conn = {};
this.timer = {};
};

DED.Queue.method("flush",function(){
if(!this.queue.length >0){
return ;
}
if(this.paused){
this.paused = false;
return;
}

var that = this;
this.currentRetry++;
var abort = function(){
that.conn.abort();
if(that.currentRetry == that.retryCount){
that.onFailure.fire();
that.currentRetry = 0;
}else{
that.flush();
}
};

this.timer = window.setTimeout(abort,this.timeout);
var callback = function(o){
window.clearTimeout(that.timer);
that.currentRetry = 0;
that.queue.shift();
that.onFlush.fire(o.responseText);
if(that.queue.length == 0){
that.onComplete.fire();
return;
}
that.flush();
};

this.conn = asyncRequest(this.queue[0]["method"],this.queue[0]["url"],callback,this.queue[0]["params"]);
}).
method("setRetryCount",function(count){
this.retryCount = count;
}).
method("setTimeout",function(time){
this.timeout = time;
}).
method("add",function(o){
this.queue.push(o);
}).
method("pause",function(){
this.paused = true;
}).
method("dequeue",function(){
this.queue.pop();
}).
method("clear",function(){
this.queue = [];
});


View Code

对应的html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body{font:100% georgia,times,serif}
h1,h2{font-weight: normal;}
#queue-items{height:1.5rem;}
#add-stuff{padding:0.5rem; background:#ddd; border:1px solid #bbb;}
#result-area{padding:0.5rem; border: 1px solid #bbb;}
</style>
</head>
<body id="exmapl">
<div id="doc">
<h1>Ajax Conection Queue</h1>
<div id="queue-items"></div>
<div id="add-stuff">
<h2>Add Requests to Queue</h2>
<ul id="adders">
<li><a href="#" id="action-01">add 01 to Queue</a></li>
<li><a href="#" id="action-02">add 02 to Queue</a></li>
<li><a href="#" id="action-03">add 03 to Queue</a></li>
<li><a href="#" id="action-04">add 04 to Queue</a></li>
</ul>
</div>
<h2>oTther Queue actions</h2>
<ul id="items">
<li><a href="#" id="flush">Flush</a></li>
<li><a href="#" id="dequeue">dequeue</a></li>
<li><a href="#" id="pause">pause</a></li>
<li><a href="#" id="clear">clear</a></li>
</ul>

<div id="result-area">
<h2>Results:</h2>
<div id="results"></div>
</div>
</div>
</body>
</html>
<script type="text/javascript" src="Bridge.js"></script>
<script>
window.onload = function(){
var q = new DED.Queue();
q.setRetryCount(5);
q.setTimeout(3000);

var items = document.getElementById("items");
var queue = document.getElementById("queue-items");
var requests = [];
q.onFlush.subscribe(function(data){
results.innerHTML = data;
requests.shift();
queue.innerHTML = requests.toString();
});
q.onFailure.subscribe(function(){
results.innerHTML += "<span style='color:red;'>Connection error</span>";
});

q.onComplete.subscribe(function(){
results.innerHTML += "<span style='color:green;'>Completed!</span>";
});

var actionDispatcher = function(element){
switch(element){
case "flush":
q.flush();
break;
case "dequeue":
requests.pop();
queue.innerHTML = requests.toString();
break;
case "pause":
q.pause();
break;
case "clear":
q.clear();
requests = [];
queue.innerHTML = "";
break;
}
};

var addRequest = function(request){
var data = request.split("-")[1];
q.add({
method:"GET",
url:"http://127.0.0.1:8020/WS_WEB/JS%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/js/ajax.json?data=" + data,
params:null
});
requests.push(data);
queue.innerHTML = requests.toString();
};

items.onclick = function(e){
var e = e || window.event;
var src = e.target || e.srcElement;
try{
e.preventDefault();
}catch(e){
e.returnValue = false;
}
if(src.id){
actionDispatcher(src.id);
}
};

var adders = document.getElementById("adders");
adders.onclick = function(){
var e = e || window.event;
var src = e.target || e.srcElement;
if(e.preventDefault){
e.preventDefault();
}else{
e.returnValue = false;
}
if(src.id)addRequest(src.id);
}

}

</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: