设计模式之 桥接模式 C# 范例

桥接模式(Bridge Pattern)是一种结构型设计模式,它将抽象与实现解耦,使得两者可以独立变化。桥接模式通常适用于以下情形:

  1. 类的功能可以在不同的维度上变化,例如在图形界面开发中,可能有不同的形状和不同的颜色,你可以在这两者之间进行独立变化。
  2. 类的实现不应该直接依赖于具体实现,而是通过接口和抽象类进行解耦。

桥接模式的结构

  1. Abstraction(抽象类):定义了一个接口,并且持有一个实现对象的引用。
  2. RefinedAbstraction(扩展抽象类):是对Abstraction的具体化,实现了不同的业务方法。
  3. Implementor(实现接口):定义了所有具体实现类必须实现的接口。
  4. ConcreteImplementor(具体实现类):实现了Implementor接口的具体类。

示例:绘图应用程序(形状与颜色分离)

我们可以创建一个图形应用程序,其中有不同的形状(如圆形和方形)和不同的颜色(如红色、绿色)。我们希望能够独立地扩展形状和颜色的种类,而不需要修改现有的代码。

1. 定义实现接口(IColor)
cs 复制代码
public interface IColor
{
    void Paint();
}
2. 实现具体颜色类(Red 和 Green)
cs 复制代码
public class Red : IColor
{
    public void Paint()
    {
        Console.WriteLine("Painting in Red");
    }
}

public class Green : IColor
{
    public void Paint()
    {
        Console.WriteLine("Painting in Green");
    }
}
3. 定义抽象类(Shape)
cs 复制代码
public abstract class Shape
{
    protected IColor color;

    public Shape(IColor color)
    {
        this.color = color;
    }

    public abstract void Draw();
}
4. 扩展具体形状(Circle 和 Square)
复制代码
cs 复制代码
public class Circle : Shape
{
    public Circle(IColor color) : base(color) { }

    public override void Draw()
    {
        Console.Write("Drawing Circle, ");
        color.Paint();
    }
}

public class Square : Shape
{
    public Square(IColor color) : base(color) { }

    public override void Draw()
    {
        Console.Write("Drawing Square, ");
        color.Paint();
    }
}
5. 客户端使用
复制代码
cs 复制代码
class Program
{
    static void Main(string[] args)
    {
        IColor red = new Red();
        IColor green = new Green();

        Shape circle = new Circle(red);  // 圆形,红色
        Shape square = new Square(green);  // 方形,绿色

        circle.Draw();  // Drawing Circle, Painting in Red
        square.Draw();  // Drawing Square, Painting in Green
    }
}

运行结果

复制代码
cs 复制代码
Drawing Circle, Painting in Red
Drawing Square, Painting in Green

分析

  • IColor 是实现接口,定义了颜色的抽象行为。
  • Red 和 Green 是具体的实现类,分别实现了不同颜色的绘制行为。
  • Shape 是抽象类,定义了形状的行为,依赖于 IColor 接口。
  • Circle 和 Square 是具体的形状类,通过构造函数接受颜色的实现对象,从而实现不同形状与颜色的组合。

总结

  • 优点:

    • 可以独立地扩展形状和颜色类,而不需要修改现有代码。
    • 减少了子类的数目,避免了复杂的类继承结构。
    • 使得系统能够更灵活地扩展新功能。
  • 缺点:

    • 增加了系统的抽象性,学习和理解曲线较为陡峭。
    • 对于非常简单的系统,可能引入不必要的复杂性。

桥接模式非常适合用在那些需要避免多重继承和扩展时,尤其是当系统的某个部分(如形状或颜色)频繁变化时。

相关推荐
博风2 小时前
9、设计模式应用举例:责任链模式:计算阶乘
设计模式·责任链模式
天天代码码天天3 小时前
屏幕翻拍满是彩色条纹?用 C# + Vulkan 做了一个去摩尔纹工具,支持单图与文件夹批量
c#·去摩尔纹
电子IT笔记3 小时前
人走了,记录不能“空白”: MES×HR 离职人员下拉回显实战
设计模式
2501_930707784 小时前
使用C#代码在 Word 文档中添加、插入或删除页面
开发语言·c#·word
淡海水5 小时前
03-03-架构篇-SGen GC架构解析
unity·架构·c#·gc·sgen
曹牧20 小时前
C#:输入的字符串格式不正确
c#
博风1 天前
8、设计模式应用举例:适配器模式:Iterator接口与Enumeration接口
设计模式·适配器模式
高晶1 天前
ARM 嵌入式 Linux 系统 U-Boot 开发与移植实战M
设计模式·程序员
根号五1 天前
JetBrains Rider 使用教程(1)新建解决方案
c#·jetbrains rider
海天鹰1 天前
C#:接收从打开方式打开的参数
c#