一种结构型设计模式。
特点:将实现与抽象分离。
优点:
- 分离了实现类和抽象类,使类之间可以进行独立变化,降低了耦合度;
- 提高了扩展性;
- 为设计提供了清晰的结构;
- 可以减少类的数量。
缺点:
- 引入了抽象的层次,增加了层次的复杂性。
适用场景:
- 需要进行解耦抽象的场景;
- 希望避免创建过多子类的场景。
示例:
using System;
/// <summary>
/// 颜色接口类
/// </summary>
public interface IColor
{
string Fill();
}
/// <summary>
/// 形状抽象类
/// </summary>
public abstract class Shape
{
protected IColor color;
protected Shape(IColor color)
{
this.color = color;
}
public abstract void Draw();
}
/// <summary>
/// 红色实现
/// </summary>
public class Red : IColor
{
public string Fill()
{
return "Red";
}
}
/// <summary>
/// 蓝色实现
/// </summary>
public class Blue : IColor
{
public string Fill()
{
return "blue";
}
}
/// <summary>
/// 正方体实现类
/// </summary>
public class Cube : Shape
{
public Cube(IColor color): base(color)
{
}
public override void Draw()
{
Console.WriteLine("绘制了一个" + color.Fill() + "Cube");
}
}
/// <summary>
/// 球体实现类
/// </summary>
public class Sphere : Shape
{
public Sphere(IColor color) : base(color)
{
}
public override void Draw()
{
Console.WriteLine("绘制了一个" + color.Fill() + "Sphere");
}
}
/// <summary>
/// 客户端
/// </summary>
public class Client
{
public static void Main(string[] args)
{
//创建颜色
IColor red = new Red();
IColor blue = new Blue();
//创建形状
Shape cube = new Cube(red);
Shape sphere = new Sphere(blue);
//绘制形状
cube.Draw();
sphere.Draw();
}
}