设计模式之迭代器模式

成绩单还是那个成绩单,但是我们想用迭代器遍历怎么做?
面向接口编程嘛我们先实现成绩单的接口

public interface IReport {
    //增加
    void add(String course,int score);
    //获取成绩信息
    String getReportInfo();
    //获得遍历对象
    ReportIterator iterator();
}

接下来成绩单的具体实现

public class Report implements IReport {
    //存放成绩的链表
    private ArrayList<IReport> reports ;
    //科目
    private String course = "";
    //分数
    private int score;
    public Report(){
        reports = new ArrayList<>();
    }
    private Report(String course,int score){
        this.course = course;
        this.score = score;
    }
    public void add(String course, int score) {
        reports.add(new Report(course,score));
    }
    
    public String  getReportInfo() {
     return  "科目"+course+"   成绩"+score;
    }
    
    public ReportIterator iterator() {
        return new ReportIterator(this.reports);
    }
}

迭代器

public class ReportIterator implements Iterator {
    private ArrayList<IReport> reports ;
    private int currentItem = 0;
    public ReportIterator(ArrayList<IReport> reports){
        this.reports = reports;
    }
    public boolean hasNext() {
        return currentItem>=reports.size()?false:true;
    }
    public IReport next() {
        return reports.get(currentItem++);
    }
}

场景类

public class Client {
    public static void main(String[] args) {
        IReport report = new Report();
        report.add("语文",30);
        report.add("数学",80);
        report.add("英语",20);
        Iterator<Report> it = report.iterator();
        while (it.hasNext()){
            System.out.println(it.next().getReportInfo());
        }
    }
}

运行结果:
科目语文 成绩30
科目数学 成绩80
科目英语 成绩20

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值