设计模式之 桥接模式 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 是具体的形状类,通过构造函数接受颜色的实现对象,从而实现不同形状与颜色的组合。

总结

  • 优点:

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

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

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

相关推荐
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
神仙别闹3 天前
基于C#+MySQL实现(WinForm)个人聊天室软件
c#
kybs19913 天前
全球灾害数据分析可视化 毕业设计-附源码66794
vue.js·spring boot·mysql·安全·django·c#·asp.net
Zane19943 天前
一个 new 就能创建对象,为什么还要拆出单例、工厂、建造者、原型四种模式?
设计模式
Polevne3 天前
C# SFTP客户端实现文件传输
c#·ssh
samble3 天前
从零搭建灌装监控系统(四):深色主题与样式系统,ResourceDictionary 统一管理
c#·wpf·mvvm·样式·工业控制
cjp5603 天前
024 . WPF MVVM类封装优化
c#
淡海水4 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
asdzx674 天前
如何使用 C# 提取 PPT 文本与图片
c#·ppt·提取文本
2501_930707784 天前
使用C#代码使用条件格式为 Excel 隔行设置颜色
c#·excel