管理聚集的方法(Add/Remove/GetChild)**僅出現在合成構件類別中**,葉構件完全不包含這些方法。

| 角色 | 說明 |
|---|---|
| 抽象構件 | 定義公共介面與預設行為,**不含**管理子物件方法 |
| 葉構件 | 無子物件,實作基本行為 |
| 合成構件 | 有子物件,提供所有管理方法 |
using System;
using System.Text;
using System.Collections;
abstract class Component
{
protected string name;
public Component(string name) => this.name = name;
public abstract void Display(int depth);
}
class Composite : Component
{
private ArrayList children = new ArrayList();
public Composite(string name) : base(name) { }
public void Add(Component c) => children.Add(c);
public 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);
}
}
class Leaf : Component
{
public Leaf(string name) : base(name) { }
public override void Display(int depth)
=> Console.WriteLine(new string('-', depth) + name);
}
public class Client
{
public static void Main()
{
Composite root = new Composite("root");
root.Add(new Leaf("Leaf A"));
root.Add(new Leaf("Leaf B"));
Composite comp = new Composite("Composite X");
comp.Add(new Leaf("Leaf XA"));
comp.Add(new Leaf("Leaf XB"));
root.Add(comp);
root.Add(new Leaf("Leaf C"));
Leaf l = new Leaf("Leaf D");
root.Add(l);
root.Remove(l);
root.Display(1);
}
}
- root -- Leaf A -- Leaf B -- Composite X ---- Leaf XA ---- Leaf XB -- Leaf C
leaf.Add(...) 直接編譯錯誤
// 介面隔離實現編譯時安全 + 統一介面
public interface IComponent { void Display(int depth); }
public interface IComposite : IComponent
{
void Add(IComponent c);
void Remove(IComponent c);
}
public class Leaf : IComponent { /* ... */ }
public class Composite : IComposite
{
private List children = new();
public void Add(IComponent c) => children.Add(c);
public void Remove(IComponent c) => children.Remove(c);
public void Display(int depth) { /* ... */ }
}