延續前文結構型模式,本文介紹 **Composite**、**Strategy**、**Iterator** 三大模式在 AWT/Swing 與 Collections Framework 中的經典應用,並探討其變體與設計權衡。
Component:抽象根節點,定義 operation()、add()、remove()(預設空實作)。Container 繼承 Component,可包含子 Component,形成遞迴樹狀結構。Component,無需區分葉節點與容器節點。標準模式將「子樹」與「非葉節點」合併為 Composite,概念易混淆。改進版引入獨立 Tree 類別:
// 改進版結構
interface Component { void operation(); }
class Leaf implements Component { ... }
class Composite implements Component { // 非葉節點
List children;
void add(Component c) { children.add(c); }
void operation() { children.forEach(Component::operation); }
}
class Tree { // 子樹/根節點
Composite root;
void operation() { root.operation(); }
}
優點:概念更清晰,處理整棵樹操作更直觀。
Container(Applet、Panel 等),持有 LayoutManager 參考。LayoutManager 定義 layoutContainer(Container)。FlowLayout、BorderLayout、GridLayout、CardLayout、GridBagLayout(實作 LayoutManager2 支援約束)。GridLayout 實例服務多個 Panel)。LayoutManager 介面)。**區別 Bridge**:Strategy 封裝**演算法**,Bridge 分離**抽象與實作**維度。
Iterator:hasNext()、next()、remove()。ListIterator 繼承 Iterator,新增雙向遍歷、索引存取、修改功能。public Iterator iterator() { return new Itr(); } // 內部類
private class Itr implements Iterator {
int cursor = 0, lastRet = -1, expectedModCount = modCount;
public boolean hasNext() { return cursor != size(); }
public Object next() {
Object next = get(cursor); // 抽象方法,由具體子類實作
checkForComodification();
lastRet = cursor++;
return next;
}
public void remove() {
if (lastRet == -1) throw new IllegalStateException();
checkForComodification();
AbstractList.this.remove(lastRet); // 抽象方法
if (lastRet < cursor) cursor--;
lastRet = -1;
expectedModCount = modCount;
}
void checkForComodification() {
if (modCount != expectedModCount) throw new ConcurrentModificationException();
}
}
設計精髓:**抽象類定義演算法骨架,委派具體資料存取(get、remove)給抽象方法,由子類實作。**
contains() 實作)、統一子類行為、應用框架擴充點。功能相似,Iterator 新增 remove()、命名更貼切。模式術語統一了團隊溝通語言。
| 模式 | 類型 | 核心價值 | 典型應用 |
|---|---|---|---|
| Composite | 結構型 | 整體-部分樹狀結構統一處理 | AWT Component/Container, 檔案系統 |
| Strategy | 行為型 | 演算法封裝與動態切換 | LayoutManager, 排序演算法, 支付策略 |
| Iterator | 行為型 | 統一遍歷介面,隔離資料結構變更 | Collections Framework, 資料庫結果集 |