再起航,我的学习笔记之JavaScript设计模式14(桥接模式)

桥接模式

桥接模式(Bridge):
在系统沿着多个维度变化的同时,又不增加其复杂度并已达到解耦

从定义上看桥接模式的定义十分难以理解,那么我们来通过示例来演示什么是桥接模式。

现在我们需要做一个导航栏随鼠标移入移出改变颜色的简单特效,但是部分选项卡全部变色,部分选项卡部分变色
再起航,我的学习笔记之JavaScript设计模式14(桥接模式)

html代码如下:

<div style=" 400px;height: 40px;">
	<span style=" 120px;height: 40px;display: block;border: 1px solid black;float: left;">用户:东城慕水</span>
	<span style=" 80px;height: 40px;display: block;border: 1px solid black;float: left;">天气:<strong>晴</strong></span>
	<span style=" 180px;height: 40px;display: block;border: 1px solid black;float: left;">当前时间:<strong>2017-8-27</strong></span>
</div>

接下我们在js中针对每个选项卡不同的特点分别处理

var spans=document.getElementsByTagName('span');
	//绑定用户特效
	spans[0].onmouseover=function(){
			this.style.color='red';
			this.style.background='#ddd';
	}
	spans[0].onmouseout=function(){
			this.style.color='#333';
			this.style.background='#f5f5f5';
	}
	spans[1].onmouseover=function(){
			this.getElementsByTagName('strong')[0].style.color='red';
			this.getElementsByTagName('strong')[0].style.background='#ddd';
	}
	spans[1].onmouseout=function(){
			this.getElementsByTagName('strong')[0].style.color='#333';
			this.getElementsByTagName('strong')[0].style.background='#f5f5f5';
	}
	spans[2].onmouseover=function(){
			this.getElementsByTagName('strong')[0].style.color='red';
			this.getElementsByTagName('strong')[0].style.background='#ddd';,
	}
	spans[2].onmouseout=function(){
			this.getElementsByTagName('strong')[0].style.color='#333';
			this.getElementsByTagName('strong')[0].style.background='#f5f5f5';
	}

我们看到虽然我们实现了功能,但是我们代码有很多相似的地方,显得特别笨重,可读性也不好,这个时候我们需要对相同的逻辑做抽象提取处理。

如果我们用面向对象的思维去编程,我们代码会更简洁,重用率会更大,可读性会更高

我们再来看我们的代码中都处理了该元素的字体颜色和背景颜色,所以我们可以把它提取出来

function changeColor(dom,color,bg){
	dom.style.color=color;
	dom.style.background=bg;
}

那么接下来我们就要处理元素的绑定事件了,然后我们要把我们的元素绑定事件和抽取的设置样式的方法连接起来,这个连接方法就是桥接方法,这种模式就是桥接模式。

var spans=document.getElementsByTagName('span');
	spans[0].onmouseover=function(){
			changeColor(this,'red','#ddd');
	}
	spans[0].onmouseout=function(){
			changeColor(this,'#333','#f5f5f5');
	}
	spans[1].onmouseover=function(){
			changeColor(this.getElementsByTagName('strong')[0],'red','#ddd');
	}
	spans[1].onmouseout=function(){
		  	changeColor(this.getElementsByTagName('strong')[0],'#333','#f5f5f5');
	}
	spans[2].onmouseover=function(){
			changeColor(this.getElementsByTagName('strong')[0],'red','#ddd');
	}
	spans[2].onmouseout=function(){
			changeColor(this.getElementsByTagName('strong')[0],'#333','#f5f5f5');
	}

现在看是不是比之前清晰了很多,如果我们想对需求做任何修改只要修改changeColor的内容就可以了。

总结

桥接模式 最主要的特点就是将实现层(比如我们这里用到的元素绑定事件)与抽象层(比如我们这里修改页面颜色的逻辑)解耦分离,使两部分可以独立化。

我们可以看出桥接模式主要是让结构之间产生联系,之前我们介绍的抽象工厂模式与创建者模式主要业务在于创建,而桥接模式主要实现解耦,使实线层与抽象层分开处理,提现了面向对象对扩展的开放及对修改的关闭原则。

当然由于桥接的添加,有时也会造成开发成本的增加。性能上也会受到一定的影响。

也谢谢大家看到这里:)如果你觉得我的分享还可以请点击推荐,分享给你的朋友让我们一起进步~

好了以上就是本次分享的全部内容,本次示例参考自JavaScript设计模式一书,让我们一点点积累一点点成长,希望对大家有所帮助。

欢迎转载,转载请注明作者,原文出处。