JavaScript设计模式之桥接模式

本文通过Toast和Message实例,展示了如何使用桥接模式分离抽象和实现,使得二者可以独立变化。通过ES5和ES6的代码实现,清晰地解释了桥接模式的应用场景和优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

适用场景:
不同的对象(A,B)有相同的行为和特征,将这部分行为和特征单独出来,形成一个新的对象C,在构建对象(A,B)时传入对象C,对象(A,B)的行为函数中调用对象C对应的行为函数。
实际应用场景:
Toast、Message 两种形态的弹窗,弹窗都有出现和隐藏等行为。
下面用代码实现一个最简单的桥接模式

  1. ES5实现方式
function Toast(node, animation) {
	this.node = node;
	this.animation = animation
}
Toast.prototype.hide =  function() {
		this.animation.hide(this.node)
}
Toast.prototype.show = function() {
	this.animation.show(this.node)
}

function Message(node, animation) {
	this.node = node;
	this.animation = animation;
	this.hide = function() {
		this.animation.hide(this.node)
	}
	this.show = function() {
		this.animation.show(this.node)
	}
}
Message.prototype.hide =  function() {
		this.animation.hide(this.node)
}
Message.prototype.show = function() {
	this.animation.show(this.node)
}

const animation = {
	hide: function(node) {
		console.log(node, ' hide')
	},
	show: function(node) {
		console.log(node, ' show')
	}
}

let toast = new Toast('div', animation)
toast.show(); //div  show
let message = new Message('div', animation)
message.hide() //div  hide
  1. ES6实现方式
class Toast {
	constructor(node, animation) {
		this.node = node;
		this.animation = animation
	}
	show() {
		this.animation.show(this.node)
	}
	hide() {
		this.animation.hide(this.node)
	}
}

class Message{
	constructor(node, animation) {
		this.node = node;
		this.animation = animation
	}
	show() {
		this.animation.show(this.node)
	}
	hide() {
		this.animation.hide(this.node)
	}
}

class Animation {
	constructor() {

	}
	hide(node) {
		console.log(node, ' hide')
	}
	show(node) {
		console.log(node, ' show')
	}
}

let animation = new Animation()
let toast = new Toast('div', animation)
toast.show(); //div  show
let message = new Message('div', animation)
message.hide() //div  hide
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值