카테고리 없음

[디자인 패턴] 이터레이터 패턴

illlilillil 2022. 4. 5. 22:06

이터레이터 패턴이란?


집합 객체 내부 구조를 노출 시키지 않고 순회하는 방법을 제공하는 패턴이다.

Collection의 구조가 바뀌게 되면 Client 구조도 바뀌게 된다.

따라서 구조를 바꾸지 않고도 순회하는 방법을 제공한다.

 

Client

public class Client {
    public static void main(String[] args) {
        Board board = new Board();
        board.addPost("디자인 패턴 게임 시작");
        board.addPost("이터레이터 패턴 시작");
        board.addPost("이터레이터 패턴 종료");
        board.addPost("디자인 패턴 게임 종료");

        Iterator<Post> recentIterator = board.getRecentIterator();
        while(recentIterator.hasNext()) {
            System.out.println("recentIterator.next().getContent() = " + recentIterator.next().getContent());
        }
    }
}

Board - ConcreteAggregate

public class Board {
    List<Post> posts = new ArrayList<>();

    public List<Post> getPosts() {
        return posts;
    }
    public void addPost(String content) {
        this.posts.add(new Post(content));
    }

    public Iterator<Post> getRecentIterator() {
        return new RecentPostIterator(this.posts);
    }
}

Post

public class Post {
    private String content;
    private LocalDateTime createdDateTime = LocalDateTime.now();

    public Post(String content) {
        this.content = content;
    }

    public LocalDateTime getCreatedDateTime() {
        return createdDateTime;
    }

    public String getContent() {
        return content;
    }
}

RecentPostIterator - ConcreteIterator

public class RecentPostIterator implements Iterator<Post> {
    private Iterator<Post> internalIterator;
    private Board board;

    public RecentPostIterator(List<Post> posts) {
        Collections.sort(posts,(p1,p2) -> p2.getCreatedDateTime()
                .compareTo(p1.getCreatedDateTime()));
        this.internalIterator = posts.iterator();
    }
    @Override
    public boolean hasNext() {
        return this.internalIterator.hasNext();
    }

    @Override
    public Post next() {
        return this.internalIterator.next();
    }
}

장점

  1. 집합 객체가 가지고 있는 객체들에 손쉽게 접근할 수 있다.
  2. 일관된 인터페이스를 사용해 여러 형태의 집합 구조를 순회할 수 있다.

단점

  1. 클래스가 늘어나고 복잡도가 증가한다.
  2. 이터레이터 방법이 추가된다면 애그리거트 쪽에 변경이 생긴다.

참고 자료

https://www.inflearn.com/course/디자인-패턴/dashboard