• 图解设计模式-Iterator模式


    使用抽象类和接口,弱化类之间的耦合,使类可以更容易组件化
    不使用具体类编程,要优先使用抽象类和接口编程
     
    角色划分:
    Iterator迭代器接口,定义遍历元素的接口,hasNext判断是否有下一个、next获得下一个值
    ConcreteIterator:迭代器具体的实现类,实现了hasNext、next两个方法,需要根据具体的被迭代对象进行自定。
    Aggregate集合接口,包含了获得Iterator迭代器的方法
    ConcreteAggregate集合的具体实现类,实现了了获得Iterator迭代器的方法
    • 定义被编列的类
    public class Book {
    
        private String name;
    
        public Book(String name){
            this.name=name;
        }
    
        public String getName() {
            return name;
        }
    }
    定义遍历接口
    public interface Iterator {
        public abstract boolean hasNext();
        public abstract Object next();
    }

    定义书架类集合

    import java.util.ArrayList;
    import java.util.List;
    
    public class BookShelf extends Aggregate {
    
        private List<Book> bookList = new ArrayList<>();
    
        public void addBook(Book book) {
            bookList.add(book);
        }
    
        public Book getIndex(int i) {
            return bookList.get(i);
        }
    
        public int getLength() {
            return bookList.size();
        }
    
        @Override
        public Iterator iterator() {
            return new BookShelfIterator(this);
        }
    }

    定义书架类对应的书架遍历类

    public class BookShelfIterator implements Iterator {
    
        private BookShelf bookShelf;
    
        private int index;
    
        public BookShelfIterator(BookShelf bookShelf) {
            this.bookShelf = bookShelf;
            this.index = 0;
        }
        @Override
        public boolean hasNext() {
            if(bookShelf.getLength()>index) {
                return true;
            }
            return false;
        }
    
        @Override
        public Object next() {
            Book book = bookShelf.getIndex(index);
            index++;
            return book;
        }
    }

    定义测试类

    public class Main {
        public static void main(String[] args){
            BookShelf bookShelf = new BookShelf();
            bookShelf.addBook(new Book("数学"));
            bookShelf.addBook(new Book("物理"));
            bookShelf.addBook(new Book("化学"));
            Iterator iterator = bookShelf.iterator();
            for(;iterator.hasNext();) {
                Book book = (Book)iterator.next();
                System.out.println(book.getName());
            }
        }
    }

    总结:被遍历的集合类(BookShelf)与遍历类(BookShelfIterator)分开定义,进行解耦,方便扩展。

    收藏文章数量从多到少与“把书读薄”是一个道理
  • 相关阅读:
    ubuntu 14.04 下试用Sublime Text 3
    闲来无事,温习一下快速排序法
    学艺不精,又被shell的管道给坑了
    ssh登录失败处理步骤
    linux文件权限整理
    使用ssh远程执行命令批量导出数据库到本地
    leetcode-easy-design-384 Shuffle an Array
    leetcode-easy-dynamic-198 House Robber-NO
    leetcode-easy-dynamic-53 Maximum Subarray
    leetcode-easy-dynamic-121 Best Time to Buy and Sell Stock
  • 原文地址:https://www.cnblogs.com/use-D/p/9545491.html
Copyright © 2020-2023  润新知