现在用到工厂模式了,因为程序员根本根本不肯知道各个最终用户实际面临的网络条件,所以不可能要求他们在开发过程中选择使用哪个处理器类,而是应该用一个工厂在运行时选择最合适的类。
var xhrManager = {
createXhrHandler:function(){
var xhr;
if (this.isOffline()) {
xhr = new offlineHandler();
}else if(this.isHighLatency()){
xhr = new QueuedHandler();
}else{
xhr = new SimpleHandler();
};
Interface.ensureImplements(xhr,AjaxHandler);
return xhr;
},
isOffline:function(){},
isHighLatency:function(){}
}
var myHandler = xhrManager.createXhrHandler();
var callback = {
success:function(responseText){},
failure:function(statusCode){}
}
myHandler.request('GET','script.php',callback);
RSS 阅读器对象,它的成员对象包括一个XHR处理器对象,一个显示对象,一个配置对象,XHR处理器类我们使用上面的xhrManager.createXhrHandler方法所创建的处理器对象,下面是一个显示类(显示对象):
var DisplayModule = new Interface('DisplayModule',['append','remove','clear']);
var ListDisplay = function(id,parent){
this.list = document.createElement('ul');
this.list.id = id;
parent.appendChild(this.list);
}
ListDisplay.prototype = {
append:function(text){
var newEl = document.createElement('li');
this.list.appendChild(newEl);
newEl.innerHTML = text;
return newEl;
},
remove:function(el){
this.list.removeChild(el);
},
clear:function(){
this.list.innerHTML = '';
}
}
var conf = {
id:'cnn-top-stories',
feedUrl:'http://.....rss',
updateInterval:60,
parent:$('feed-readers')
}
var FeedReader = function(display,xhrHandler,conf){
this.display = display;
this.xhrHandler = xhrHandler;
this.conf = conf;
this.startUpdates();
}
FeedReader.prototype = {
fetchFeed:function(){
var _this = this;
var callback = {
success:function(text,xml){
_this.parseFeed(text,xml);
},
failure:function(status){
_this.showError(status);
}
};
this.xhrHandler.request('GET',this.conf.feedUrl,callback);
},
parseFeed:function(responseText,responseXML){
this.display.clear();
var items = responseXML.getElementsByTagName('item');
for(var i= 0,len=items.length;i<len;i++){
var title = items[i].getElementsByTagName('title')[0];
var link = items[i].getElementsByTagName('link')[0];
this.display.append('<a href="'+link.firstChild.data+'">'+title.firstChild.data+'</a>');
}
},
showError:function(status){
this.display.clear();
this.display.append('Error fetching feed.');
},
stopUpdates:function(){
clearInterval(this.interval);
},
startUpdates:function(){
this.fetchFeed();
var _this = this;
this.interval = setInterval(function(){_this.fetchFeed();},
this.conf.updateI