桥接模式是一种结构型模式,将抽象与实现与实现分离,使他们可以独立变化,通过组合关系替代继承关系,符合合成复用原则,可以总结为一句话,将m*n个实现类的设计转换成m+n个实现类的设计。
namespace Designmode.Bridge
{
/// <summary>
/// 颜色的接口
/// </summary>
public interface IColor
{
/// <summary>
/// 获取颜色
/// </summary>
/// <returns></returns>
string GetColor();
}
}
namespace Designmode.Bridge
{
/// <summary>
/// 图形抽象类
/// </summary>
public abstract class Shape
{
/// <summary>
/// 图形颜色
/// </summary>
public IColor Color { set; get; }
/// <summary>
/// 设置颜色
/// </summary>
/// <param name="color"></param>
/// <exception cref="NotImplementedException"></exception>
public void SetColor(IColor color)
{
this.Color = color;
}
/// <summary>
/// 绘制
/// </summary>
public abstract void Draw();
}
}
namespace Designmode.Bridge
{
/// <summary>
/// 正方形
/// </summary>
public class Square : Shape
{
/// <summary>
/// 绘制
/// </summary>
public override void Draw()
{
Console.WriteLine($"square with {this.Color.GetColor()}");
}
}
}
namespace Designmode.Bridge
{
public class Circle : Shape
{
/// <summary>
/// 绘制
/// </summary>
public override void Draw()
{
Console.WriteLine($"Circle with {this.Color}");
}
}
}
namespace Designmode.Bridge
{
/// <summary>
/// 颜色的具体实现
/// </summary>
public class RedColor : IColor
{
/// <summary>
/// 获取颜色
/// </summary>
/// <returns></returns>
public string GetColor()
{
return "red";
}
}
}
namespace Designmode.Bridge
{
/// <summary>
/// 颜色的具体实现
/// </summary>
public class GreenColor:IColor
{
/// <summary>
/// 获取颜色
/// </summary>
/// <returns></returns>
public string GetColor()
{
return "Green";
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Designmode.Adapter;
using Designmode.Bridge;
namespace Designmode
{
class Program
{
static void Main(string[] args)
{
#region 桥接模式
//红色
IColor red = new RedColor();
//红色正方形
Shape square = new Square();
square.SetColor(red);
square.Draw();
#endregion
}
}
}