js设计模式之桥接模式

桥接模式主要是将实现层(元素绑定的事件)与抽象层(修饰页面的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();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值