桥接模式主要是将实现层(元素绑定的事件)与抽象层(修饰页面的ui逻辑)解耦
例如:
管管赤脚不害怕 等级1 消息5
先在要实现鼠标移动上去有hover的效果,那么我们一步一步实现:
function g(tag){
return document.getElementByTagName(tag);
}
var spans=g('span');
spans[0].onmouseover=function(){
this.style.color='red';
this.background='#eedede';
}
spans[0].onmouseout=function(){
this.style.color='#dedede';
this.style.background='red';
}
spans[1].onmouseover=function(){
this.document.getElenmentByTagName('strong')[0].style.color='#dedede';
this.document.getElenmentByTagName('strong')[0]style.background='#ddd';
}
spans[1].onmouseout=function(){
this.document.getElenmentByTagName('strong')[0].style.color='#swswsw';
this.document.getElenmentByTagName('strong')[0]style.background='red';
}
……
代码太冗余了!!!!现在我们对改变颜色的部分进行公共功能提取:
function changeColor(dom,color,bg){
dom.style.color=color;
dom.style.background=bg;
}
下面我们通过匿名回调函数,将获取到的this传递到changecolor函数中,
var spans = g(span);
spans[0].onmouseover=function(){
changeColor(this,'red','#ddd')
}
spans[0].onmouseout=function(){
changeColor(this,'#ddd','red')
}
spans[1].onmouseover=function(){
changeColor(this.document.getElementByTagName('strong')[0],'red','#ddd')
}
……
另外,桥接模式的强大之处对于多元化对象也很实用。
例如:在简单的游戏中,人,球,精灵都具有一套相同的动作,x,y坐标变化,球和精灵的颜色绘制方式相同。
//多维变量类
//运动单元
function Speed(x,y){
this.x=x;
this.y=y;
}
Speed.prototype.run=function(){……}
//着色单元
function Color(cl){
this.color=cl;
}
Color.prototype.draw=function(){……}
//变形单元
function Shape(sp){
this.shape=sp;
}
Shape.prototype.change=function(){……}
//说话单元
function Speak(wd){
this.word=wd;
}
Speak.prototype.say=function(){……}
//创建球类
function Ball (x,y,c){
this.speed=new Speed(x,y);
this.color=new Color(c);
}
Ball.prototype.init=function(){
this.speed.run();
this.color.draw();
}
//创建人物
function people(x,y,w){
this.speed=new Speed(x,y);
this.word=new Speak(w);
}
People.prototype.init=function(){
this.speed.run();
this.word.say();
}
//实例化人物
var p = new People(10,20,'hahah');
p.init();