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

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

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

桥接模式的结构

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

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

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

1. 定义实现接口(IColor
cs 复制代码
public interface IColor
{
    void Paint();
}
2. 实现具体颜色类(RedGreen
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. 扩展具体形状(CircleSquare
复制代码
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 是实现接口,定义了颜色的抽象行为。
  • RedGreen 是具体的实现类,分别实现了不同颜色的绘制行为。
  • Shape 是抽象类,定义了形状的行为,依赖于 IColor 接口。
  • CircleSquare 是具体的形状类,通过构造函数接受颜色的实现对象,从而实现不同形状与颜色的组合。

总结

  • 优点

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

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

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

相关推荐
从孑开始8 小时前
ManySpeech.MoonshineAsr 使用指南
人工智能·ai·c#·.net·私有化部署·语音识别·onnx·asr·moonshine
Deschen8 小时前
设计模式-外观模式
java·设计模式·外观模式
YuanlongWang8 小时前
C# 中,依赖注入(DI)的实现方式
c#
SmartSoftHelp开发辅助优化10 小时前
C# WinForm 编程高手:程序,进程,线程。程序,窗体,UI,后台。是如何协调工作的?深度解析>SmartSoftHelp魔法精灵工作室
microsoft·ui·c#
future_studio12 小时前
聊聊 Unity(小白专享、C# 小程序 之 加密存储)
开发语言·小程序·c#
c#上位机12 小时前
MefBootstrapper在Prism引导程序中的使用
c#·wpf·prism
恋红尘15 小时前
设计模式详解
设计模式
玩泥巴的15 小时前
.NET驾驭Word之力:基于规则自动生成及排版Word文档
c#·word·.net·com互操作
SunnyDays101116 小时前
C# 实现高保真 Excel 转 PDF(无需 Office 环境)
经验分享·c#·excel转pdf
攻城狮CSU16 小时前
C# 数据加载专题 之泛型序列化
java·servlet·c#