行为型模式的应用(一)迭代器模式(Iterator)

电视机遥控器是一个迭代器的现实应用,通过它可以实现对电视频道集合的遍历操作,电视机可以看成一个存储频道的聚合对象。试模拟电视机遥控器的实现,绘制出相应的类图。20软2

20软2
第一步,定义一个抽象聚合类Television
public interface Television 
{
   public TVIterator createIterator();
}

第二步,定义一个抽象迭代器TVIterator
public interface TVIterator 
{
   public void setChannel(int i);
   public Object currentChannel();
   public void next();
   public void previous();
   public boolean isLast();
   public boolean isFirst();
}

第三步,定义一个具体聚合类TCLTelevision
public class TCLTelevision implements Television 
{
   public Object[] obj= {"CCTV1","CCTV2","CCTV3","CCTV4","CCTV5"};
   public TVIterator createIterator() 
   {
    return new TCLIterator();
   }
//具体迭代器TCLIterator:
   private class TCLIterator implements TVIterator 
   {
      private int currentIndex = 0;
      public void setChannel(int i) 
      {
   	   currentIndex=i;
      }
      public void next() {
          if(currentIndex<obj.length){
              currentIndex++;
          }
      }
      public void previous() {
          if(currentIndex>0){
              currentIndex--;
          }
      }
      public boolean isLast() {
          return currentIndex ==obj.length;
      }
      public Object currentChannel() {
          return obj[currentIndex];
      }
      public boolean isFirst() {
          return currentIndex==0;
      }

   }
}
第四步,定义一个具体迭代器TCLIterator
public class TCLIterator implements TVIterator 
{
   private int currentIndex = 0;
   public void setChannel(int i)  {}
   public void next() {}
   public void previous() {}
   public boolean isLast() {
       return false;
   }
   public Object currentChannel() {
       return false;
   }
   public boolean isFirst() {
       return false;
   }
}

第五步,定义用户测试类Client
public class Client {
    public static void main(String[] args) {
        Television tv;
        tv=new TCLTelevision();
        TVIterator i =tv.createIterator();
        System.out.println("电视频道:");
        while(!i.isLast()){
            System.out.println(i.currentChannel().toString());
            i.next();
        }
    }
}

测试结果:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秃头小霸王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值