JavaScript 设计模式之桥接模式

桥接模式

通过桥接模式,我们可以将业务逻辑与元素的事件解耦,也可以更灵活的创建一些对象

倘若我们有如下代码

javascript 复制代码
const dom = document.getElementById('#test')

// 鼠标移入移出事件
// 鼠标移入时改变背景色和字体颜色
dom.onmouseenter = function() { 
  this.style.color = 'white'
  this.style.backgroundColor = 'black'
}

// 鼠标移出时恢复背景色和字体颜色
dom.onmouseleave = function () {
  this.style.color = 'black'
  this.style.backgroundColor = 'white'
}

这里我们不难看出有部分代码是重复的,只是改变了字体颜色跟背景色,这耦合度就高起来了,我们可以是这样

javascript 复制代码
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')
}

继续优化

javascript 复制代码
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')
}

多元化

在使用不同角色有相同公用的方法时可以使用这种多元化来处理

javascript 复制代码
const Speed = (x, y) => {
  this.x = x
  this.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()
}
...

通过桥接灵活的创建一个对象,针对不同的对象处理不同的业务逻辑,更灵活处理差异

相关推荐
一枚前端小能手28 分钟前
「周更第3期」实用JS库推荐:Lodash
前端·javascript
艾小码28 分钟前
Vue组件到底怎么定义?全局注册和局部注册,我踩过的坑你别再踩了!
前端·javascript·vue.js
鹏多多36 分钟前
前端复制功能的高效解决方案:copy-to-clipboard详解
前端·javascript
uhakadotcom40 分钟前
Rollup 从0到1:TypeScript打包完全指南
前端·javascript·面试
Mintopia1 小时前
实时语音转写 + AIGC:Web 端智能交互的技术链路
前端·javascript·aigc
2503_928411561 小时前
9.15 ES6-变量-常量-块级作用域-解构赋值-箭头函数
前端·javascript·es6
Mintopia1 小时前
Next.js 单元测试究竟该选 JTest 还是 Vitest?
前端·javascript·next.js
遂心_1 小时前
深入浅出 querySelector:现代DOM选择器的终极指南
前端·javascript·react.js
遂心_1 小时前
DOM元素内容修改全攻略:从innerHTML到现代API的最佳实践
前端·javascript·react.js
Aomnitrix1 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式