//Facade模式实例
var net=new Object();
net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;
net.ContentLoader=function(url,onload,onerror){
this.url=url;
this.req=null;
this.onload=onload;
this.onerror=(onerror) ? onerror : this.defaultError;
this.loadXMLDoc(url);
net.ContentLoader.prototype={
loadXMLDoc:function(url){
if (window.XMLHttpRequest){
this.req=new XMLHttpRequest();
} else if (window.ActiveXObject){
this.req=new ActiveXObject("Microsoft.XMLHTTP");
}
if (this.req){
try{
var loader=this;
this.req.onreadystatechange=function(){
loader.onReadyState.call(loader);
}
this.req.open('GET',url,true);
this.req.send(null);
}catch (err){
this.onerror.call(this);
}
}
},
onReadyState:function(){
var req=this.req;
var ready=req.readyState;
if (ready==net.READY_STATE_COMPLETE){
var httpStatus=req.status;
if (httpStatus==200 || httpStatus==0){
this.onload.call(this);
}else{
this.onerror.call(this);
}
}
},
defaultError:function(){
alert("error fetching data!"
+"\n\nreadyState:"+this.req.readyState
+"\nstatus: "+this.req.status
+"\nheaders: "+this.req.getAllResponseHeaders());
}
}
//Adapter模式实例
var xhr = new XMLHttpRequest();
xhr.open("GET", "myData.xml");
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
alert(xhr.responseXML);
}
}
xhr.send(null);
//Observer模式实例
window.onloadListeners=new Array();
window.addOnLoadListener(listener){
window.onloadListeners[window.onloadListeners.length]=listener;
}
window.onload=function(){
for(var i=0;i<window.onloadListeners.length;i++){
var func=window.onlloadListeners[i];
func.call();
}
}
//Singleton模式实例
var SingletonObj = {
property1: value1,
property2: value2,
...
method1:function(){
...
}
method2:function(){
...
}
...
}
function getSingletonObj() {
if(!top.SingletonObj) {
var top.SingletonObj = {
...
}
top.SingletonObj.init(...);
}
return top.SingletonObj;
}
//Command模式实例
function buttonOnclickHandler(event){
var data=calculate();
showData(dataTable,data);
}
function ajaxOnloadHandler(){
var data=calculate();
showData(otherDataTable,data);
}
function calculate(){
var data=new Array();
data[0]=6;
data[1]=data[0]/3;
data[2]=data[0]*data[1]+7;
return data;
}
function showData(table,data){
var newRow=createTableRow(table);
for (var i=0;i<data.length;i++){
createTableCell(newRow,data[i]);
}
}
buttonDiv.onclick=buttonOnclickHandler;
poller.onload=ajaxOnloadHandler;
//MVC应用实例
function Button(value,domEl){
this.domEl=domEl;
this.value=value;
this.domEl.buttonObj=this;
this.domEl.onclick=this.clickHandler;
}
Button.prototype.clickHandler=function(){
var buttonObj=this.buttonObj;
var value=(buttonObj && buttonObj.value) ?
buttonObj.value : "unknown value";
alert(value);
}