8.桥接模式
桥接模式(Bridge Pattern)的主要目的是把“抽象”和“实现”拆分成两个独立维度,让它们可以分别扩展
适合使用桥接模式的场景
- 一个系统有两个或多个变化维度(如通知类型与发送渠道)
- 不希望用继承硬编码所有组合,避免组合爆炸
- 需要在运行时切换底层实现
- 希望把高层业务和底层实现解耦
实现层接口与实现类
interface Sender {
send(content: string): void;
}
class EmailSender implements Sender {
send(content: string): void {
console.log(`[Email] ${content}`);
}
}
class FeishuSender implements Sender {
send(content: string): void {
console.log(`[Feishu] ${content}`);
}
}抽象层与扩展抽象
abstract class Notification {
constructor(protected sender: Sender) {}
abstract notify(message: string): void;
}
class ErrorNotification extends Notification {
notify(message: string): void {
this.sender.send(`ERROR: ${message}`);
}
}
class InfoNotification extends Notification {
notify(message: string): void {
this.sender.send(`INFO: ${message}`);
}
}使用示例
new ErrorNotification(new EmailSender()).notify("支付失败");
new InfoNotification(new FeishuSender()).notify("发布成功");