【Java设计模式】迭代器模式

【Java设计模式】迭代器模式

一、概述

Java中的迭代器设计模式提供了一种在不暴露聚合对象内部表示的情况下,顺序访问其元素的方法。这种行为模式对于高效的集合遍历至关重要。

二、详细解释及实际示例

  1. 实际示例
    • 想象一下参观一个拥有大量书籍的图书馆,这些书籍被组织在不同的区域,如小说、非小说、科学等。与其自己搜索每一个书架,图书管理员为你提供了每个区域的特定指南或数字目录。这个指南就像一个“迭代器”,允许你逐节浏览书籍,甚至跳转到特定类型的书籍,而无需知道书籍在书架上的具体组织方式。每个指南处理其所在区域的遍历,提供了一种一致且高效的访问书籍的方式,就像迭代器设计模式在软件应用程序中为遍历不同的数据结构提供了统一的方法一样。
  2. 通俗解释
    • Java迭代器设计模式提供了一种方法,可以顺序访问集合的元素,而无需暴露其底层结构。这种模式在Java编程中广泛用于高效的数据访问。
  3. 维基百科解释
    • 在面向对象编程中,迭代器模式是一种设计模式,其中使用迭代器来遍历容器并访问容器的元素。

三、Java中迭代器模式的编程示例

在我们的Java迭代器设计模式示例中,主要类是TreasureChest,它包含物品。这展示了如何在Java中实现和使用迭代器来进行高效的集合遍历。

public class TreasureChest {
    private final List<Item> items;
    public TreasureChest() {
        items = List.of(
                new Item(ItemType.POTION, "Potion of courage"),
                new Item(ItemType.RING, "Ring of shadows"),
                new Item(ItemType.POTION, "Potion of wisdom"),
                new Item(ItemType.POTION, "Potion of blood"),
                new Item(ItemType.WEAPON, "Sword of silver +1"),
                new Item(ItemType.POTION, "Potion of rust"),
                new Item(ItemType.POTION, "Potion of healing"),
                new Item(ItemType.RING, "Ring of armor"),
                new Item(ItemType.WEAPON, "Steel halberd"),
                new Item(ItemType.WEAPON, "Dagger of poison"));
    }
    public Iterator<Item> iterator(ItemType itemType) {
        return new TreasureChestItemIterator(this, itemType);
    }
    public List<Item> getItems() {
        return new ArrayList<>(items);
    }
}

这里是Item类:

public class Item {
    private ItemType type;
    private final String name;
    public Item(ItemType type, String name) {
        this.setType(type);
        this.name = name;
    }
    @Override
    public String toString() {
        return name;
    }
    public ItemType getType() {
        return type;
    }
    public final void setType(ItemType type) {
        this.type = type;
    }
}
public enum ItemType {
    ANY, WEAPON, RING, POTION
}

Iterator接口非常简单。

public interface Iterator<T> {
    boolean hasNext();
    T next();
}

在下面的示例中,我们展示了不同类型的迭代器。

@Slf4j
public class App {
    private static final TreasureChest TREASURE_CHEST = new TreasureChest();
    private static void demonstrateTreasureChestIteratorForType(ItemType itemType) {
        LOGGER.info("------------------------");
        LOGGER.info("Item Iterator for ItemType " + itemType + ": ");
        var itemIterator = TREASURE_CHEST.iterator(itemType);
        while (itemIterator.hasNext()) {
            LOGGER.info(itemIterator.next().toString());
        }
    }
    private static void demonstrateBstIterator() {
        LOGGER.info("------------------------");
        LOGGER.info("BST Iterator: ");
        var root = buildIntegerBst();
        var bstIterator = new BstIterator<>(root);
        while (bstIterator.hasNext()) {
            LOGGER.info("Next node: " + bstIterator.next().getVal());
        }
    }
    private static TreeNode<Integer> buildIntegerBst() {
        var root = new TreeNode<>(8);
        root.insert(3);
        root.insert(10);
        root.insert(1);
        root.insert(6);
        root.insert(14);
        root.insert(4);
        root.insert(7);
        root.insert(13);
        return root;
    }
    public static void main(String[] args) {
        demonstrateTreasureChestIteratorForType(RING);
        demonstrateTreasureChestIteratorForType(POTION);
        demonstrateTreasureChestIteratorForType(WEAPON);
        demonstrateTreasureChestIteratorForType(ANY);
        demonstrateBstIterator();
    }
}

程序输出:

13:36:37.087 [main] INFO com.iluwatar.iterator.App -- ------------------------
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Item Iterator for ItemType RING: 
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Ring of shadows
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Ring of armor
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- ------------------------
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Item Iterator for ItemType POTION: 
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of courage
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of wisdom
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of blood
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of rust
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of healing
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- ------------------------
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Item Iterator for ItemType WEAPON: 
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Sword of silver +1
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Steel halberd
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Dagger of poison
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- ------------------------
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Item Iterator for ItemType ANY: 
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of courage
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Ring of shadows
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of wisdom
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of blood
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Sword of silver +1
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of rust
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of healing
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Ring of armor
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Steel halberd
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Dagger of poison
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- ------------------------
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- BST Iterator: 
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 1
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 3
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 4
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 6
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 7
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 8
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 10
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 13
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 14

四、何时在Java中使用迭代器模式

在Java中使用迭代器设计模式的情况包括:

  1. 访问聚合对象的内容而不暴露其内部表示。
  2. 支持对聚合对象的多次遍历。
  3. 为遍历不同的聚合结构提供统一的接口。

五、迭代器模式在Java中的实际应用

  1. Java集合框架广泛使用迭代器来允许以不同的方式遍历集合。
  2. 数据库经常使用迭代器来导航通过SQL查询获取的数据记录。
  3. java.util.Iterator
  4. java.util.Enumeration

六、迭代器模式的好处和权衡

好处:

  1. 减少了数据结构和用于迭代的算法之间的耦合。
  2. 为遍历各种类型的数据结构提供了统一的接口,增强了代码的可重用性和灵活性。

权衡:

  1. 使用迭代器对象的开销可能会比直接遍历方法略微降低性能。
  2. 复杂的聚合结构可能需要复杂的迭代器,这可能难以管理或扩展。

七、源码下载

迭代器模式示例代码下载

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值