首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

從 Java 類庫看設計模式(四):Composite、Strategy 與 Iterator 模式深度解析

     編輯:Java 相關知識

前言

延續前文結構型模式,本文介紹 **Composite**、**Strategy**、**Iterator** 三大模式在 AWT/Swing 與 Collections Framework 中的經典應用,並探討其變體與設計權衡。

Composite 模式:AWT Component-Container 樹狀結構

標準結構

  • 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(); }
}

優點:概念更清晰,處理整棵樹操作更直觀。

Strategy 模式:AWT LayoutManager 布局策略封裝

核心結構

  • Context:Container(Applet、Panel 等),持有 LayoutManager 參考。
  • Strategy 介面:LayoutManager 定義 layoutContainer(Container)。
  • Concrete Strategies:FlowLayout、BorderLayout、GridLayout、CardLayout、GridBagLayout(實作 LayoutManager2 支援約束)。

優勢

  • 演算法與容器解耦,執行時動態切換布局策略。
  • 單一策略可被多容器共用(如同一 GridLayout 實例服務多個 Panel)。
  • 易於擴充自訂布局(實作 LayoutManager 介面)。

缺點與權衡

  • 客戶端必須知曉所有策略類別以便選擇。
  • 策略與 Context 常緊耦合(需傳遞容器特定資料),難以完全封裝於抽象策略中。
  • 策略生命週期由客戶端控制,概念上應從屬於 Context。

**區別 Bridge**:Strategy 封裝**演算法**,Bridge 分離**抽象與實作**維度。

Iterator 模式:Collections Framework 統一遍歷介面

介面體系

  • Iterator:hasNext()、next()、remove()。
  • ListIterator 繼承 Iterator,新增雙向遍歷、索引存取、修改功能。

實作機制:AbstractList 範例

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)給抽象方法,由子類實作。**

抽象類 vs 介面的設計哲學

  • 介面:最大靈活性,無預設實作,適合定義類型契約。
  • 抽象類:提供預設服務(如 contains() 實作)、統一子類行為、應用框架擴充點。

Enumeration vs Iterator

功能相似,Iterator 新增 remove()、命名更貼切。模式術語統一了團隊溝通語言。

小結

模式類型核心價值典型應用
Composite結構型整體-部分樹狀結構統一處理AWT Component/Container, 檔案系統
Strategy行為型演算法封裝與動態切換LayoutManager, 排序演算法, 支付策略
Iterator行為型統一遍歷介面,隔離資料結構變更Collections Framework, 資料庫結果集
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved