迭代器模式(Iterator Pattern)

2024/3/31 Java进阶

提供一种方法顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表示。也就是提供遍历方法。

# 1、迭代器模式案例

为手机号码提供一个迭代器用于遍历每一位值

public interface Iterator {
    int next();
    boolean hasNext();
}
1
2
3
4

数值迭代器

public class NumberIterator implements Iterator{
    private int[] phoneNumber;
    private int index;

    public NumberIterator(String phoneNumber) {
        int[] result = new int[phoneNumber.length()];
        for (int i = 0; i < phoneNumber.length(); i++) {
            result[i] = Character.getNumericValue(phoneNumber.charAt(i));
        }
        this.phoneNumber = result;
    }

    @Override
    public int next() {
        return phoneNumber[index++];
    }

    @Override
    public boolean hasNext() {
        return index < phoneNumber.length;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

准备一个手机

public interface Phone {
    Iterator createIterator();
}

// 为手机提供迭代器方式
public class HuaweiPhone implements Phone{
    private String phoneNumber;

    public HuaweiPhone(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    @Override
    public Iterator createIterator() {
        return new NumberIterator(phoneNumber);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class ClientTest {
    public static void main(String[] args) {
        Phone phone = new HuaweiPhone("154256445102");
        Iterator iterator = phone.createIterator();

        while (iterator.hasNext()){
            System.out.print(iterator.next()+"\t");
        }
    }
}
/**
 * 输出结果:1	5	4	2	5	6	4	4	5	1	0	2
 * /
1
2
3
4
5
6
7
8
9
10
11
12
13