桥接模式(将抽象与其实现隔离开来,以便二者独立变化)
function sendInfo(element){ var id=element.id; ajax("GET","info.json?id="+id,function(result){ //... }); //... };
上例的ajax请求与sendInfo函数可以拆分开
function sendInfo(element){ var id=element.id, callback=function(result){ //... }; sendInfoBridge(id,callback); } function sendInfoBridge(id,callback){ ajax("GET","info.json?id="+id,function(result){ callback(result); }); }
组合模式(用一条命令在多个对象上激发复杂的或递归的行为),组合对象和叶对象
条件一:存在一批组织成某种层次体系的对象
条件二:希望对这批对象或其中一部分对象进行操作
组合对象
var Composite=new Interface('Composite',['add','remove','getChild']); var GalleryItem=new Interface('GalleryItem',['hide','show']); var DynamicGallery=function(id){ this.children=[]; this.element=document.createElement('div'); this.element.id=id; this.element.className='dynamic-gallery'; } DynamicGallery.prototype={ add:function(child){ Interface.ensureImplements(child,Composite,GalleryItem); this.children.push(child); this.element.appendChild(child.getElement()); }, remove:function(child){ for(var node,i=0;node=this.getChild(i);i++){ if(node==child){ this.children.splice(i,1); break; } } this.element.removeChild(child.getElement()); }, getChild:function(i){ return this.children[i]; }, hide:function(){ for(var node,i=0;node=this.getChild(i);i++){ node.hide(); } this.element.style.display='none'; }, show:function(){ this.element.style.display='block'; for(var node,i=0;node=this.getChild(i);i++){ node.show(); } }, getElement:function(){ return this.element; } };
叶对象
var GalleryImage=function(src){ this.element=dicument.createElement('img'); this.element.className='gallery-image'; this.element.src=src; } GalleryImage.prototype={ add:function(){}, remove:function(){}, getChild:function(){}, hide:function(){ this.element.style.display='none'; }, show:function(){ this.element.style.display=''; }, getElement:function(){ return this.element; } };
var topGallery=new DynamicGallery('top-gallery'); topGallery.add(new GalleryImage('/img/image-1.jpg')); topGallery.add(new GalleryImage('/img/image-2.jpg')); topGallery.add(new GalleryImage('/img/image-3.jpg')); var vacationPhotos=new DynamicGallery('vacation-photos'); for(var i=0;i<30;i++){ vacationPhotos.add(new GalleryImage('/img/vac/image-'+i+'.jpg')); } topGallery.add(vacationPhotos); topGallery.show(); vacationPhotos.hide();