桥接模式:在系统沿着多个维度变化的同时,又不增加其复杂度并已达到解耦。(先抽象提取共用部分,然后将实现与抽象通过桥接方法链接在一起,以此实现解耦的作用)
最主要的特点:将实现层(如元素绑定的事件)与抽象层(如修饰页面UI逻辑)解耦分离,使两部分可以独立变化
比如添加一些事件交互,页面中的一些小小细节改变常常因逻辑相似导致大片臃肿的代码。如以下代码
对于用户名,鼠标改变直接改变背景色,但是对于用户消息这类,只能改变里面的文字内容颜色。
<script>
//为用户名绑定特效
var spans=document.getElementsByTagName('span');
spans[0].onmouseover=function(){
this.style.color="red";
this.style.background="yellow";
}
spans[0].onmouseout=function(){
this.style.color="white";
this.style.background="blue";
}
//为用户信息里面的数字绑定特效
spans[1].onmouseover=function(){
this.getElementsByTagName('strong')[0].style.color="red";
this.getElementsByTagName('strong')[0].style.background="yellow";
}
spans[1].onmouseout=function(){
this.getElementsByTagName('strong')[0].style.color="white";
this.getElementsByTagName('strong')[0].style.background="blue";
}
</script>
要注意对相同的逻辑做抽象提取处理,重用率、可读性更高。
上述代码有很大一部分都是相似的,比如它们都处理每个部件中的某个元素,都是处理该元素下的字体颜色和背景颜色。
对这个相似点进行抽象提取,解除其与事件中的this的耦合。
<script>
//抽象
function changeColor(dom,color,bgColor){
dom.style.color=color;
dom.style.background=bgColor;
}
//为用户名绑定特效
var spans=document.getElementsByTagName('span');
spans[0].onmouseover=function(){
// this.style.color="red";
// this.style.background="yellow";
changeColor(this,"red","yellow");
}
spans[0].onmouseout=function(){
// this.style.color="white";
// this.style.background="blue";
changeColor(this,"white","blue");
}
//为用户信息里面的数字绑定特效
spans[1].onmouseover=function(){
// this.getElementsByTagName('strong')[0].style.color="red";
// this.getElementsByTagName('strong')[0].style.background="yellow";
changeColor(this.getElementsByTagName('strong')[0],"red","yellow");
}
spans[1].onmouseout=function(){
// this.getElementsByTagName('strong')[0].style.color="white";
// this.getElementsByTagName('strong')[0].style.background="blue";
changeColor(this.getElementsByTagName('strong')[0],"white","blue");
}
</script>