美文网首页
js设计模式-桥接模式

js设计模式-桥接模式

作者: hzl的学习小记 | 来源:发表于2019-08-13 16:28 被阅读0次

桥接模式

什么是桥接模式
把事物对象和其具体行为、具体特征分离开来,使它们可以各自独立的变化

例子:
男生 女生
钢琴 吉他
钢琴能演奏,吉他能演奏
男生能让乐器演奏,女生能让乐器演奏
钢琴是乐器, 吉他是乐器
需要一种方式让对象和行为分离,便于随意拼接

function Boy(instrument) {
    this.sayHi = function() {
        console.log('hi, 我是男生')
    }
// 有一个功能叫playInstrument, 没有具体乐器
   this.playInstrument = function() {
        instrument.play()
    }
}

function Girl(instrument) {
    this.sayHi = function() {
        console.log('hi, 我是女生')
    }
// 有一个功能叫playInstrument, 没有具体乐器
    this.playInstrument = function() {
        instrument.play()
    }
}

function Piano() {
    this.play = function() {
        console.log('钢琴开始演奏')
    }
}

function Guitar() {
    this.play = function() {
        console.log('吉他开始演奏')
    }
}

let piano = new Piano()
let guitar = new Guitar()
let pianoBoy = new Boy(piano)
pianoBoy.playInstrument()
let guitarGirl = new Girl(guitar)
guitarGirl.playInstrument()

实际一点的案例

页面有 Toast、Message 两种形态的弹窗,弹窗都有出现和隐藏等行为,这些行为可以使用不同风格的动画。

function Toast(node, animation) {
    this.node = node
    this.animation = animation
}
//调用 animation 的show方法
Toast.prototype.show = function() {
    this.animation.show(this.node)   
}
//调用 animation 的hide方法
Toast.prototype.hide = function() {
    this.animation.hide(this.node)   
}

function Message(node, animation) {
    this.node = node
    this.animation = animation
}
//调用 animation 的show方法
Message.prototype.show = function() {
    this.animation.show(this.node)   
}
//调用 animation 的hide方法
Message.prototype.hide = function() {
    this.animation.hide(this.node)   
}

const Animations = {
    bounce: {
        show: function(node) { console.log(node + '弹跳着出现') }
        hide: function(node) { console.log(node + '弹跳着消失') }
    },
    slide: {
        show: function(node) { console.log(node + '滑着出现') }
        hide: function(node) { console.log(node + '滑着消失') }        
    }
}

let toast = new Toast('元素1', Animations.bounce )
toast.show()

let messageBox = new Message('元素2', Animations.slide)
messageBox.hide()

相关文章

  • js设计模式-桥接模式

    桥接模式 什么是桥接模式把事物对象和其具体行为、具体特征分离开来,使它们可以各自独立的变化 例子:男生 女...

  • 设计模式-桥接模式

    设计模式-桥接模式 定义 桥接模式(Bridge Pattern)也称为桥梁模式、接口(Interface)模式或...

  • 桥接模式

    设计模式:桥接模式(Bridge)

  • 设计模式——桥接模式

    设计模式——桥接模式 最近公司组件分享设计模式,然而分配给我的是桥接模式。就在这里记录我对桥接模式的理解吧。 定义...

  • JS设计模式之桥接模式

    定义 桥接(Bridge)是用于把抽象化与实现化解耦,使得二者可以独立变化。这种类型的设计模式属于结构型模式,它通...

  • 设计模式js篇--桥接模式

    一、定义 通过提供抽象化和现实化之间的桥接结构,实现二者的解耦。2个角色:(1)扩充抽象类(2)具体实现类 二、举...

  • 设计模式之桥接模式

    设计模式之桥接模式 1. 模式定义 桥接模式又称柄体模式或接口模式,它是一种结构性模式。桥接模式将抽象部分与实现部...

  • 桥接模式

    介绍 桥接模式(Bridge Pattern) 也称为桥梁模式,是结构型设计模式之一。桥接模式的作用就是连接 "两...

  • Java设计模式——桥接模式

    Java设计模式之桥接模式 回顾 上一期分享了适配器模式,主要为了实现解耦 桥接模式 简介 桥接模式是对象的结构模...

  • 设计模式-桥接模式

    桥接模式介绍 桥接模式(Bridge Pattern)也称为桥梁模式,是结构型设计模式之一。顾名思义其与现实中的桥...

网友评论

      本文标题:js设计模式-桥接模式

      本文链接:https://www.haomeiwen.com/subject/sgjbjctx.html