迭代器模式

迭代器模式(别名:游标)

 提供一种方法顺序访问一个聚合对象中的各个元素,而又不需要暴露该对象的内部表示。

一 、 概述

迭代器模式是遍历集合的成熟模式,迭代器模式的关键是将遍历集合的任务交给一个称作迭代器的对象。 

二、迭代器模式的结构与使用 

模式的结构中包括四种角色:

集合( Aggregate ):
具体集合( ConcreteAggregate
迭代器( Iterator
具体迭代器( ConcreteIterator
模式UML类图

1.集合(Aggregate:

   在这里我们使用java.util包中的Collection接口作为模式中的集合角色。Java所有的集合都实现了该接口。

2.具体集合(ConcreteAggregate:

   在这里我们使用java.util包中的HashSet类的实例作为模式中的具体集合角色。

3.迭代器(Iterator) :

  在本问题中,我们使用的迭代器是java.util包中的Itertator接口 。

4.具体迭代器(ConcreteIterator

  HashSet创建的集合可以使用iterator ()方法返回一个实现Iterator接口类的实例,即一个具体迭代器。

5.应用 Application.java_1

import java.util.*;

public classApplication{

    public static void main(String args[]){

       int n=20;

       int sum=0; 

       Collection<RenMinMony> set=new HashSet<RenMinMony>(); 

       for(inti=1;i<=n;i++){

          if(i==n/2||i==n/5||i==n/6)

            set.add(new RenMinMony(100,false));

          else

            set.add(new RenMinMony(100,true));

       }

       Iterator<RenMinMony> iterator=set.iterator();    

       intjia=1,zhen=1;

       System.out.println("保险箱共有"+set.size()+"张人民币");

       int k=0;

       while(iterator.hasNext()){

           RenMinMony money=iterator.next();

           k++;

           if(money.getIsTrue()==false){

              System.out.println(""+k+"张是假币,被销毁");

              iterator.remove();

              k++;

           }

       }

       System.out.println("保险箱现有真人民币"+set.size()+",总价值是:"); 

       iterator=set.iterator();

       while(iterator.hasNext()){

           RenMinMony money=iterator.next();

           sum=sum+money.getValue();

       }

       System.out.println(sum+"");

   }

}

5.应用 Application.java_2

class RenMinMony{

   int value;

   private booleanisTrue;

   RenMinMony(intvalue,boolean b){

      this.value=value;

       isTrue=b;

   }

   public booleangetIsTrue(){

      return isTrue;

   }

   public intgetValue(){

      return value;

   }

}

三、迭代器模式的优点 

用户使用迭代器访问集合中的对象,而不需要知道这些对象在集合中是如何表示及存储的。
用户可以同时使用多个迭代器遍历一个集合。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值