JavaScript结构型设计模式---桥接模式

参考书籍:JavaScript设计模式
桥接模式最主要的特点是将实现层(如元素绑定的事件)与抽象层(如修饰页面UI逻辑)解耦分离,使两部分可以独立变化,避免需求的改变造成对象内部的修改。可以看出桥接模式主要是对机构之间的结构。
页面组件的特效实例

//提取共同点--桥接函数(事件)
function changeColor(dom, color, bg) {
    dom.style.color = color;
    dom.style.backgroundColor = bg;
}
//桥接方法--匿名回调
demos[0].onclick = function () {
    changeColor(this, 'red', 'purple')
}
demos[0].onmouseover = function () {
    changeColor(this, '#ddd', 'green')
}

多元化对象
桥接模式的强大之处不仅仅在此,甚至对于多维的变化也同样适用。比如我们书写一个canvas跑步游戏的时候,对于游戏中的人,小精灵,小球等一系列的实物都是有动作单元,而他们的每个动作实现起来方式又都是统一的,比如人,精灵和球的运动其实就是位置坐标x, y 的变化,球的颜色与精灵的色彩的绘制方式都是相似的,这样我们可以将这些多维变化部分提出来, 作为一个抽象的运动单元进行保存,而当我们创建实体时,将需要的每个抽象动作单元通过桥接, 链接在一起运作。这样他们不会相互影响并且该方式降低了他们之间的耦合。

//多维变量类
//运动单元
function Speed(x, y) {
    this.x = x;
    this.y = y;
}
Speed.prototype.run=function(){
    console.log('运动起来');
}
//着色单元
function Color(cl) {
    this.color = cl;
}
Color.prototype.draw=function(){
    console.log('绘制色彩');
}
//变形单元
function Shape(sp) {
    this.shape = sp;
}
Shape.prototype.change=function(){
    console.log('改变形状');
}
//说话单元
function Speak(wd) {
    this.word = wd;
}
Speak.prototype.say=function(){
    console.log('ta说');
}

于是我们创建了一个球类:运动+着色

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, s) {
    //实现运行单元
    this.speed = new Speed(x, y);
    this.speak = new Speak(s);
}
People.prototype.init=function(){
    //实现运行
    this.speed.run();
    this.speak.say();
}

精灵: 运动+着色+说话

function Spirite(x, y, c, s) {
    //实现运行单元
    this.speed = new Speed(x, y);
    this.speak = new Speak(s);
    this.color = new Color(c);
}
Spirite.prototype.init = function () {
    //实现运行
    this.speed.run();
    this.speak.say();
    this.color.draw();

}

测试

var b = new Ball(10, 20, 'red');
b.init();
var p = new People(10, 20, 'I said: ');
p.init();
var s = new Spirite(10, 20, 'red','I said: ');
s.init();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值