본문 바로가기
SW 공부/Design Patterns

[디자인패턴] Iterator pattern (반복자 패턴)

by 꼬냉상 2022. 8. 28.

Purpose of Iterator Pattern (반복자 패턴의 목적)

aka) Cursor

- Allows for access to the elements of an aggregate object without allowing access to its underlying representation.

- 외부에 노출 없이, 자료형 관계없이, collection에서 객체를 꺼낼 때 사용

 

Design Principle (디자인원칙)

- Single Responsibility Principle (단일 책임의 원칙)

- A class should have only one reason to change

  * Aggregate and Iteration – two different responsibilities

  * Cohesion

 

Iterator pattern (반복자 패턴)

- Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. 

- 기본 표현을 노출하지 않고 Aggregate 객체의 요소에 순차적으로 액세스 할 수 있는 방법을 제공

- 자바의 Iterator를 사용하면 됨 : java.util.Iterator interface

public interface Iterator {
    boolean hasNext();
    Object next();
    void remove();
}

 

Related Patterns

- Iterator can traverse a Composite. Visitor can apply an operation over a Composite. 

- Polymorphic Iterators rely on Factory Methods to instantiate the appropriate Iterator subclass. 

- Memento is often used in conjunction with Iterator. An Iterator can use a Memento to capture the state of an iteration. The Iterator stores the Memento internally. 

 

Quiz) TV의 채널 collection을 TunedChannels과 FavoriteChannels 클래스로 구별하여 관리하고자 한다. TunedChannels 클래스에는 순방향 혹은 역방향으로 순 회할 수 있는 TunedChannelIterator를 생성하는 메쏘드가 제공된다. 이와 유사하게 FavoriteChennelIterator가 FavoriteChannels 클래스를 위해 제공된다. TunedChannelIterator와 FavoriteChannelIterator 클래스에는 역방향 순회용 prev(), 순방향 순회용 next() 메쏘드가 제공된다.

Iterator 패턴을 기반으로 상기 모델을 TV 클래스와 함께 클래스 다이어그램으로 그리시오.

 

본 글은 개인의 S/W 구조설계 역량 강화를 위한 학습 목적으로 정리된 내용입니다.
일부 타/개인 단체에 저작권이 있는 자료를 포함하고 있으므로, 절대 영리 목적으로 사용하실 수 없습니다.

 

반응형

댓글