桥接模式与解耦合

桥接模式

有一个需求,要对一个组件实现鼠标滑过特效,但组件内部有很多元素,每个元素滑过的特效可能有一定的共同点,此时我们可以将共同点抽象出来

例:

function changeColor(dom, color, bg){
    dom.style.color = color
    dom.style.background = bg
}
然后,可以用一个匿名回调函数构建事件与业务的桥梁,降低耦合度,不要直接将changeColor作为事件的回调函数,否则就没有意义了,因为又耦合了
HTML:第一个span滑过要有特效,第二个span滑过时,内部的第三个span要有特效
<body>
    <span>111111</span><br>
    <span>
        <span>9999999</span>
        <span>9999999</span>
        <span>9999999</span>
        <span>9999999</span>
        <span>9999999</span>
    </span><br>
    <span>111111</span>
</body>

JS

const spans = document.getElementsByTagName("span")
spans[0].onmouseover = function(){
    changeColor(this, "red", "#ddd")
}
spans[0].onmouseout = function(){
    changeColor(this, "#333", "#ffffff")
}
// 当只有组件内部某个元素需要绑定特效时
spans[1].onmouseover = function(){
    changeColor(this.getElementsByTagName("span")[2], "red", "#ddd")
}
spans[1].onmouseout = function(){
    changeColor(this.getElementsByTagName("span")[2], "#333", "#ffffff")
}

多元化对象

当我们创建一些对象,他们之间部分功能是相同的,但部分功能是不同的,将需要的每个抽象功能桥接在一起,这样就互不影响且降低了耦合度
功能:
// 运动功能
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 Speek(wd){
    this.word = wd
}
Speek.prototype.say = function(){
    console.log("书写")
}

实现类:

// 创建一个球的类,可以运动,可以着色
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, f){
    this.speed = new Speed(x, y)
    this.font = new Speek(f)
}
Ball.prototype.init = function(){
    this.speed.run()
    this.font.say()
}
// 创建一个精灵的类,可以运动,可以着色,可以改变形状
function Spirite(x, y, c, s){
    this.speed = new Speed(x, y)
    this.color = new Color(c)
    this.shape = new Shape(s)
}
Spirite.prototype.init = function(){
    this.speed.run()
    this.color.draw()
    this.shape.change()
}

当我们创建一个人时,直接实例化一个人的类,这样就可以说话运动了

const p = new People(10, 12, 16)
p.init()

 

posted @ 2021-12-03 14:21  邢韬  阅读(47)  评论(0编辑  收藏  举报