玩转JavaScript:桥梁设计模式实战解析
最编程
2024-02-16 11:24:26
...
桥接模式
通过桥接模式,我们可以将业务逻辑与元素的事件解耦,也可以更灵活的创建一些对象
倘若我们有如下代码
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'
}
这里我们不难看出有部分代码是重复的,只是改变了字体颜色跟背景色,这耦合度就高起来了,我们可以是这样
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')
}
继续优化
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')
}
多元化
在使用不同角色有相同公用的方法时可以使用这种多元化来处理
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()
}
...
通过桥接灵活的创建一个对象,针对不同的对象处理不同的业务逻辑,更灵活处理差异
推荐阅读
-
玩转设计模式:状态模式实战解析
-
玩转Spring Boot里的设计模式——实战揭秘【委派模式】及其实用应用
-
探探应用实战解析:专为寻找附近异性与兴趣相投者设计" 用户需求与烦恼: 1. 身边异性朋友寥寥,扩大交友圈子无从下手 2. 初来乍到新城市,渴望交到本地朋友或异性知己 3. 遇到心仪对象,想提前了解彼此是否志趣相投 4. 对心动异性不敢主动搭讪,害怕被拒场面尴尬 产品界面: - a: 设置选项 - b: 主页 - c: 配对成功的通知 探探的核心功能: - 基于位置和兴趣标签,推荐附近的高匹配度陌生人,显示真人照片、基本信息(如昵称、年龄、职业、距离)、共同点(如通讯录好友、兴趣爱好)。 - 双方需同时向右滑动表示“喜欢”才能配对成功,可进行文字、表情、真心话问答、图片/视频等多种交流方式。 产品特点与独特之处: - 陌生人间的选择操作直观易懂,左滑忽略、右滑喜欢。 - 系统不会记录“喜欢”历史,仅当双方都喜欢才会成功配对并展开后续交流。 - 每个陌生人只会展示一次,确保每一次抉择都有决定性意义。 - 提供屏蔽手机联系人的功能,满足用户既想脱单又不愿让熟人知晓的需求,符合探探专注陌生人社交平台定位。 商业模式探讨:
-
玩转JavaScript:桥梁设计模式实战解析
-
实战JavaScript设计模式:观察者模式初探
-
用JavaScript实现策略模式的设计思路解析