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()
}
...

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

相关推荐
软件技术NINI1 分钟前
基于PHP和MySQL的快递代收点管理系统的设计与实现
开发语言·javascript·数据库·mysql·毕业设计·php·毕设
Dovis(誓平步青云)12 分钟前
一个分区超温就全棚浇水,控制系统怎样按区下策略
开发语言·前端·javascript·人工智能·机器学习
是2的10次方啊43 分钟前
设计模式与生活⑤:天冷了,给电动车套件挡风被
设计模式
DevNote_1 小时前
1C1G 服务器从零配置实录(附完整命令)
linux·运维·服务器·javascript·adb·ssh·gmssh
Dovis(誓平步青云)1 小时前
切换语言后按钮被截断,本地化审计怎样发现长度风险
开发语言·前端·javascript·人工智能·机器学习·华为·harmonyos
CappuccinoRose1 小时前
拖拽交互体系
前端·javascript·css·html·交互·1024程序员节
开开心心就好1 小时前
免安装PDF盖章工具,透明度和位置可调
运维·服务器·前端·javascript·pdf·ocr·1024程序员节
2501_944521599 小时前
Ramda 跨端三方库仓颉适配全流程
开发语言·javascript·flutter·php
Ken_111511 小时前
小体积附件下载正常,大附件下载异常
javascript
变与不变80612 小时前
jQuery怎么使用
前端·javascript