其他分享
首页 > 其他分享> > 图解设计模式 --适应设计模式

图解设计模式 --适应设计模式

作者:互联网

代码Github连接 :https://github.com/tangbi123/Tab-Design-Pattern

一、iterator模式

Iterator模式用于在数据集合中按照顺序遍历集合。

1、思路点

1)iterator可以将遍历与实现分离开开
2)next
返回当前元素,指向下一个元素

2、角色

1)Iterator
按顺序逐个遍历元素的接口(API)
2)ConcreteIterator
实现Iterator角色所定义的接口(API)
3)Aggregate
定义创建Iterator角色的接口(API)
4)ConcreteAggregate
实现Aggregate角色所定义的接口(API)
在这里插入图片描述

3、示例

 图1.1 Iterator示例

名字说明
Aggregate表示集合的接口
Iterator遍历集合的接口
Book表示书的类
BookShelf表示书架的类
BookShelfIterator遍历书架的类
Main测试程序行为的类

代码清单

  1. Iterator
public interface MyIterator {
    public abstract boolean hasNext();
    public abstract Object next();
}

2)Aggregate

public interface Aggregate {
    public abstract MyIterator myIterator();
}
  1. Book : class
public class Book {
    private String name;

    public Book(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}
  1. BookShelf
public class BookShelf implements Aggregate{

    private ArrayList<Book> books;

    public BookShelf() {
        this.books = new ArrayList<>();
    }

    public Book getBookAt(int index){
        return books.get(index);
    }

    public void appendBook(Book book){
        this.books.add(book);
    }
    public int getLength(){
        return books.size();
    }

    @Override
    public MyIterator myIterator() {
        return new BookShelfIterator(this);
    }

}

5)BookShelfIterator

public class BookShelfIterator implements MyIterator{
    private BookShelf bookShelf;
    private int index;
    public BookShelfIterator(BookShelf bookShelf){
        this.bookShelf = bookShelf;
        this.index = 0;
    }
    @Override
    public boolean hasNext() {
        if(index < bookShelf.getLength()){
            return true;
        }
        return false;
    }

    @Override
    public Object next() {
        Book book = bookShelf.getBookAt(index);
        index++;
        return book;
    }
}

6)main

public class main {
    public static void main(String[] args) {
        BookShelf bookShelf = new BookShelf();
        bookShelf.appendBook(new Book("test1"));
        bookShelf.appendBook(new Book("test2"));
        bookShelf.appendBook(new Book("test3"));
        bookShelf.appendBook(new Book("test4"));
        MyIterator myIterator = bookShelf.myIterator();
        while(myIterator.hasNext()){
            Book book = (Book)myIterator.next();
            System.out.println(book.getName());
        }
    }
}

二、Adaper模式

git config lfs.https://github.com/tangbi123/Tab-Design-Pattern.git/info/lfs.locksverify false

标签:index,图解,return,--,BookShelf,Book,bookShelf,设计模式,public
来源: https://blog.csdn.net/weixin_44919162/article/details/117260502