# 桥接模式
属于结构型模式。
将抽象部分(主体类)与实现部分(主题类成员)分离,使它们都可以独立的变化。
适用性:
- 不希望使用继承导致系统类的个数急剧增加
- 一个类存在多个维度的变化,且多个维度都需要进行扩展
# 类图
![img]()
# 代码
# 拥有桥接关系的类
| namespace StructuralPattern_BridgePattern |
| { |
| |
| |
| |
| public abstract class Color |
| { |
| |
| |
| |
| public abstract void MyColor(); |
| } |
| } |
| namespace StructuralPattern_BridgePattern |
| { |
| |
| |
| |
| public class Red : Color |
| { |
| public override void MyColor() |
| { |
| Console.WriteLine("Color: Red"); |
| } |
| } |
| } |
| namespace StructuralPattern_BridgePattern |
| { |
| |
| |
| |
| public abstract class Shape |
| { |
| protected Color MyColor; |
| |
| public Shape(Color color) |
| { |
| MyColor = color; |
| } |
| |
| |
| |
| |
| public abstract void MyShape(); |
| |
| } |
| } |
| namespace StructuralPattern_BridgePattern |
| { |
| |
| |
| |
| public class Square : Shape |
| { |
| public Square(Color color) : base(color) { } |
| |
| public override void MyShape() |
| { |
| Console.WriteLine("Shape: Square"); |
| MyColor.MyColor(); |
| } |
| } |
| } |
# 测试
| namespace StructuralPattern_BridgePattern |
| { |
| public class Program |
| { |
| private static void Main() |
| { |
| Shape shape = new Square(new Red()); |
| shape.MyShape(); |
| } |
| } |
| } |
运行结果:
Shape: Square
Color: Red