組合模式最關鍵的地方是簡單對像和復合對像實現相同的接口
/// <summary>
/// 圖形抽像類
/// </summary>
public abstract class Graphics
{
public string Name { get; set; }
public Graphics(string name)
{
this.Name = name;
}
public abstract void Draw();
public abstract void Add(Graphics g);
public abstract void Remove(Graphics g);
}
簡單圖形
/// <summary>
/// 簡單圖形類——線
/// </summary>
public class Line : Graphics
{
public Line(string name)
: base(name)
{ }
// 重寫父類抽像方法
public override void Draw()
{
Console.WriteLine("畫線:" + Name);
}
public override void Add(Graphics g)
{
throw new Exception("不能向簡單圖形Line添加其他圖形");
}
public override void Remove(Graphics g)
{
throw new Exception("不能向簡單圖形Line移除其他圖形");
}
}
/// <summary>
/// 簡單圖形類——圓
/// </summary>
public class Circle : Graphics
{
public Circle(string name)
: base(name)
{ }
// 重寫父類抽像方法
public override void Draw()
{
Console.WriteLine("畫圓:" + Name);
}
public override void Add(Graphics g)
{
throw new Exception("不能向簡單圖形Circle添加其他圖形");
}
public override void Remove(Graphics g)
{
throw new Exception("不能向簡單圖形Circle移除其他圖形");
}
}
複雜圖形
/// <summary>
/// 複雜圖形,由一些簡單圖形組成,假設該複雜圖形由兩條線組成
/// </summary>
public class ComplexGraphics : Graphics
{
private List<Graphics> complexGraphicsList = new List<Graphics>();
public ComplexGraphics(string name)
: base(name)
{ }
/// <summary>
/// 複雜圖形的畫法
/// </summary>
public override void Draw()
{
foreach (Graphics g in complexGraphicsList)
{
g.Draw();
}
}
public override void Add(Graphics g)
{
complexGraphicsList.Add(g);
}
public override void Remove(Graphics g)
{
complexGraphicsList.Remove(g);
}
}
實際執行
class MyClass
{
static void Main(string[] args)
{
ComplexGraphics complexGraphics = new ComplexGraphics("複雜圖形 - 兩條線段組成的複雜圖形");
complexGraphics.Add(new Line("線段A"));
complexGraphics.Add(new Line("線段C"));
// 顯示複雜圖形的畫法
Console.WriteLine("複雜圖形的繪製:");
Console.WriteLine("---------------------");
complexGraphics.Draw();
Console.WriteLine("複雜圖形繪製完成");
Console.WriteLine("---------------------");
}
}
優點:
組合模式介面都一致,可以存在容器統一處理
缺點:複雜度會增加
沒有留言:
張貼留言