X.d 笔记

小Web,大世界

0%

设计模式(16):迭代器模式 Iterator

好像很多语言里面都有Iterator接口什么的,如果hasNext()方法返回true时,就可以用next()方法取对象了。

迭代器模式 Iterator

题义:迭代子模式可以顺序访问一个聚集中的元素而不必暴露聚集的内部表象。多个对象聚在一起形成的总体称之为聚集,聚集对象是能够包容一组对象的容器对象。迭代子模式将迭代逻辑封装到一个独立的子对象中,从而与聚集本身隔开。迭代子模式简化了聚集的界面。每一个聚集对象都可以有一个或一个以上的迭代子对象,每一个迭代子的迭代状态可以是彼此独立的。迭代算法可以独立于聚集角色变化。

问题:

Need to “abstract” the traversal of wildly different data structures so that algorithms can be defined that are capable of interfacing with each transparently.

意图:

  • Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
  • The C++ and Java standard library abstraction that makes it possible to decouple collection classes and algorithms.
  • Promote to “full object status” the traversal of a collection.
  • Polymorphic traversal

代码

在JAVA里面想用此模式,用Iterator接口都可以了。想想平时使用Iterator的场景貌似都是遍历Map和ResultSet.哦,基本就是这样的场景了,需要遍历结构相同的数据的时候使用。

例:网上看到的例子都太复杂了,我这里直接实现接口实现一个迭代器,假如我要为公司里面的100号人进行摇奖,使用迭代器如下,为100个人的ID去算

代码一:奖金

public class Data{

    private int id;

    private String prize;

    public Data(int id, String prize) {
        super();
        this.id = id;
        this.prize = prize;
    }

    @Override
    public String toString() {
        return "ID为 " + id + " 的用户, 中了 "+this.prize+" 的奖金!";
    }
}

代码二:迭代器

public class DataMap  implements Iterator<Data>{

    private int total = 0;
    private DecimalFormat df = new DecimalFormat("0.00");

    public DataMap(int total) {
        this.total = total;
    }

    @Override
    public boolean hasNext() {
        return this.total > 1;
    }

    @Override
    public Data next() {
        total--;
        return new Data(total,df.format(Math.random()*100));
    }

}

代码三:摇奖

public static void main(String[] args) {
    Iterator<Data> it = new DataMap(100);
    while(it.hasNext()){
        Data data = it.next();
        System.out.println(data);
    }
}

小结

迭代器模式 Iterator

  • 使用频率:
    在Java中遍历对象时,一般会不得已使用,可能是Java太方便了,很少自己定义一些类去实现Iterator接口。

  • 利弊影响:
    由于不是数组类型,所以无法使用for循环,但一些语言里面有foreach可以直接遍历哦。