javascript设计模式_桥接模式

桥接模式:在系统沿着多个维度变化的同时,又不增加其复杂度并已达到解耦。(先抽象提取共用部分,然后将实现与抽象通过桥接方法链接在一起,以此实现解耦的作用

最主要的特点:将实现层(如元素绑定的事件)与抽象层(如修饰页面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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值