码迷,mamicode.com
首页 > 编程语言 > 详细

javascript设计模式8

时间:2015-01-20 23:50:06      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:

桥接模式(将抽象与其实现隔离开来,以便二者独立变化)

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();

 

javascript设计模式8

标签:

原文地址:http://www.cnblogs.com/sdgjytu/p/4229793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!