建设牌安全带官方网站,o2o网站建设机构,做网站对服务器要求,专门帮忙做网站的公司桥接模式
通过桥接模式#xff0c;我们可以将业务逻辑与元素的事件解耦#xff0c;也可以更灵活的创建一些对象
倘若我们有如下代码
const dom document.getElementById(#test)// 鼠标移入移出事件
// 鼠标移入时改变背景色和字体颜色
dom.onmouseenter function() { th…桥接模式
通过桥接模式我们可以将业务逻辑与元素的事件解耦也可以更灵活的创建一些对象
倘若我们有如下代码
const dom document.getElementById(#test)// 鼠标移入移出事件
// 鼠标移入时改变背景色和字体颜色
dom.onmouseenter function() { this.style.color whitethis.style.backgroundColor black
}// 鼠标移出时恢复背景色和字体颜色
dom.onmouseleave function () {this.style.color blackthis.style.backgroundColor white
}这里我们不难看出有部分代码是重复的只是改变了字体颜色跟背景色这耦合度就高起来了我们可以是这样
const changeColor (dom, color, val){dom.style[color] val
}
const dom document.getElementById(#test)
dom.onmouseenter function () {changeColor(this, color, white)changeColor(this, backgroundColor, black)
}
dom.onmouseleave function () {changeColor(this, color, black)changeColor(this, backgroundColor, white)
}
继续优化
const changeColor (dom, color, val){dom.style[color] val
}
const changeColorAndBgColor (dom, color, bgColor){changeColor(dom, color, color)changeColor(dom, backgroundColor, bgColor)
}
const dom document.getElementById(#test)
dom.onmouseenter function () {changeColorAndBgColor(this, white, black)
}
dom.onmouseleave function () {changeColor(this, black, white)
}
多元化
在使用不同角色有相同公用的方法时可以使用这种多元化来处理
const Speed (x, y) {this.x xthis.y y
}
Speed.prototype.run function () { console.log(first run)
}
// TODO其他内容
const Color color {this.color color
}
Color.prototype.draw function () {console.log(first draw)
}
// TODO其他内容
const Speak word {this.word word
}
Speak.prototype.say function () {console.log(first say)
}
// TODO其他内容// 创建一个 球
const Ball function (x, y, color) {this.speed new Speed(x, y)this.color new Color(color)
}
Ball.prototype.init function () {this.speed.run()this.color.draw()
}// 创建一个人
const People function (x, y, say) {this.speed new Speed(x, y)this.speak new Speak(say)
}
People.prototype.init function () {this.speed.run()this.speak.say()
}
...
通过桥接灵活的创建一个对象针对不同的对象处理不同的业务逻辑更灵活处理差异