C#中的桥接模式

桥接模式:将抽象部分与它的实现部分分离,使它们都可以独立地变化。

主要代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
///<桥接模式>
public interface TV
{
public void TuneChannel();
}
public abstract class RemoteControl
{
public TV _tv;
public void SetTV(TV tv)
{
this._tv = tv;
}
public abstract void SetChannel();
}
public class ConcreteRemote : RemoteControl
{
public override void SetChannel()
{
_tv.TuneChannel();
}
}
public class SonyTV : TV
{
public void TuneChannel()
{
Console.WriteLine("SonyTV.TuneChannel is called");
}
}
public class SamsungTV : TV
{
public void TuneChannel()
{
Console.WriteLine("SamsungTV.TuneChannel is called");
}
}
///<桥接模式/>

模式结构

角色 代码示例 职责
抽象部分 RemoteControl 定义高层控制逻辑
扩展抽象 ConcreteRemote 实现抽象部分的接口
实现者接口 TV 定义底层实现接口
具体实现者 SonyTV/SamsungTV 实现具体业务功能

关键点

  1. 双重分离
    1
    2
    3
    4
    public abstract class RemoteControl {  // 抽象部分
    public TV _tv; // 桥接点:持有实现者引用
    // ...
    }
  2. 运行时绑定
    1
    2
    remote.SetTV(sony);    // 动态切换实现
    remote.SetChannel();
  3. 独立演化
  • 新增遥控器类型只需继承RemoteControl

  • 新增电视品牌只需实现TV接口

使用

1
2
3
4
5
6
7
8
9
10
11
12
RemoteControl remoteControl = new ConcreteRemote();

TV Sony = new SonyTV();

TV Samsung = new SamsungTV();

remoteControl.SetTV(Sony);
remoteControl.SetChannel();

remoteControl.SetTV(Samsung);
remoteControl.SetChannel();

优势分析

特性 实现方式 优势
解耦抽象与实现 通过桥接接口连接 两者可独立变化
扩展性 新增电视品牌不影响遥控器逻辑 符合开闭原则
组合优于继承 使用对象组合而非多层继承 避免类爆炸
动态切换 SetTV()方法 运行时更换实现

应用场景
- 需要多维度扩展的系统

- 抽象和实现都应支持独立扩展

- 避免永久绑定抽象与实现

- 常见案例:

    - 不同操作系统+不同文件格式

    - 多种支付方式+多种支付渠道

    - 不同形状+不同渲染引擎

要点记忆:

  • RemoteControl持有TV接口引用(桥接核心)

  • ConcreteRemote将操作委托给TV实现

  • 通过SetTV()动态切换具体电视品牌

  • 新增电视品牌只需实现TV接口