zhangdizhangdi

桥接模式

定义

桥接模式(Bridge Pattern),是用于把抽象化与实现化解耦,使得二者可以独立变化

实现

js
//输入设备
class Gestures {
  constructor(output) {
    this.output = output
  }

  tap() {
    this.output.click()
  }
  swipe() {
    this.output.move()
  }
  pan() {
    this.output.drag()
  }
  pinch() {
    this.output.zoom()
  }
}

class Mouse {
  constructor(output) {
    this.output = output
  }

  click() {
    this.output.click()
  }
  move() {
    this.output.move()
  }
  down() {
    this.output.drag()
  }
  wheel() {
    this.output.zoom()
  }
}

// 输出设备
class Screen {
  click() {
    console.log('Screen select')
  }
  move() {
    console.log('Screen move')
  }
  drag() {
    console.log('Screen drag')
  }
  zoom() {
    console.log('Screen zoom in')
  }
}

class Audio {
  click() {
    console.log('Sound oink')
  }
  move() {
    console.log('Sound waves')
  }
  drag() {
    console.log('Sound screetch')
  }
  zoom() {
    console.log('Sound volume up')
  }
}

const screen = new Screen()
const audio = new Audio()

const hand = new Gestures(screen)
const mouse = new Mouse(audio)

hand.tap()
hand.swipe()
hand.pinch()

mouse.click()
mouse.move()
mouse.wheel()
执行结果
Screen select
Screen move
Screen zoom in
Sound oink
Sound waves
Sound volume up

参考