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

25
五月
2021

代码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

TAG

网友评论

共有访客发表了评论
请登录后再发布评论,和谐社会,请文明发言,谢谢合作! 立即登录 注册会员