背景
- 桥接多个维度时
- 实现@抽象类:
- 子类继承产生基础维度
- 构造器传参其它维度(1-n)
- 方法提炼或交互多个维度
示例
using static System.Console;
namespace DesignPattern_Bridge
{
// 颜色维度,便于替换传参
public interface IColor { void Show(); }
public class Blue : IColor
{
public void Show() => WriteLine("in blue color.");
}
public class Red : IColor
{
public void Show() => WriteLine("in red color.");
}
// 桥接颜色和形状维度变化
public abstract class Shape
{
protected readonly IColor Color;
// 允许多个接口传参
public Shape(IColor color)
{
Color = color;
}
// 提炼或交互接口,多接口传参时也必须
public virtual void Draw() { }
}
public class Circle : Shape
{
public Circle(IColor color) : base(color) { }
public override void Draw()
{
Write("One circle is drawn ");
Color.Show();
}
}
public class Square : Shape
{
public Square(IColor color) : base(color) { }
public override void Draw()
{
Write("One circle is drawn ");
Color.Show();
}
}
public class Client
{
public void Execute()
{
// 绿色长方形时,应
// - 增加IColor的子类Green,不影响旧代码
// - 增加Shape的子类Rectangle,不影响旧代码
// - 本类颜色改为绿色,影响旧代码,必须
// - 本类形状改为长方形,影响旧代码,必须
var color = new Red();
var shape = new Circle(color);
shape.Draw();
ReadKey();
}
}
class Program
{
static void Main(string[] args)
{
var client = new Client();
client.Execute();
}
}
}
网友评论