# 桥接模式

属于结构型模式。
将抽象部分(主体类)与实现部分(主题类成员)分离,使它们都可以独立的变化。

适用性:

  • 不希望使用继承导致系统类的个数急剧增加
  • 一个类存在多个维度的变化,且多个维度都需要进行扩展

# 类图

img

# 代码

# 拥有桥接关系的类

namespace StructuralPattern_BridgePattern
{
    /// <summary>
    /// 颜色
    /// </summary>
    public abstract class Color
    {
        /// <summary>
        /// 颜色
        /// </summary>
        public abstract void MyColor();
    }
}
namespace StructuralPattern_BridgePattern
{
    /// <summary>
    /// 红色
    /// </summary>
    public class Red : Color
    {
        public override void MyColor()
        {
            Console.WriteLine("Color: Red");
        }
    }
}
namespace StructuralPattern_BridgePattern
{
    /// <summary>
    /// 形状
    /// </summary>
    public abstract class Shape
    {
        protected Color MyColor;
        public Shape(Color color)
        {
            MyColor = color;
        }
        /// <summary>
        /// 形状
        /// </summary>
        public abstract void MyShape();
    }
}
namespace StructuralPattern_BridgePattern
{
    /// <summary>
    /// 正方形
    /// </summary>
    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

更新于 阅读次数

请我喝[茶]~( ̄▽ ̄)~*

Maikire 微信支付

微信支付

Maikire 支付宝

支付宝

Maikire 贝宝

贝宝