abstract class Component
{
protected string name;
public Component(string name)
{
this.name = name;
}
public abstract void Add(Component c);
public abstract void Remove(Component c);
public abstract void Display(int depth);
}
class Leaf : Component
{
public Leaf(string name) : base(name) { }
public override void Add(Component c)
{
Console.WriteLine("Leaf cannot add");
}
public override void Remove(Component c)
{
Console.WriteLine("Leaf cannot remove");
}
public override void Display(int depth)
{
Console.WriteLine(new string('-', depth) + name);
}
}
class Composite : Component
{
public Composite(string name) : base(name) { }
IList<Component> children = new List<Component>();
public override void Add(Component c)
{
children.Add(c);
}
public override void Remove(Component c)
{
children.Remove(c);
}
public override void Display(int depth)
{
Console.WriteLine(new string('-', depth) + name);
foreach (Component c in children)
{
c.Display(depth + 2);
}
}
}
// 業務代碼:
Composite root = new Composite("高新興");
Leaf gc = new Leaf("財務部");
Leaf gi = new Leaf("IT 部");
Leaf ghr = new Leaf("人力");
root.Add(gc);
root.Add(gi);
root.Add(ghr);
Composite pa = new Composite("平安事業部");
Leaf pahr = new Leaf("人力");
Composite payf = new Composite("研發");
Leaf jg = new Leaf("交通");
payf.Add(jg);
pa.Add(pahr);
pa.Add(payf);
root.Add(pa);
root.Display(1);
- Y 公司
---財務部
---IT 部
---人力
--- X 事業部
-----人力
-----研發
-------交通
組合模式定義了基本物件和組合物件,基本物件可以被組合到更復雜的組合物件,而組合物件又可以被組合,不斷遞回;
可以在各個基本物件中定義內部對繼承的抽象類的實作,而用戶并不需要知道是處理一個基本物件還是組合物件,因此用不著寫一些判斷陳述句,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/241173.html
標籤:.NET技术
下一篇:設計模式 - 18)單例模式
