이터레이터패턴 (1)

디자인 패턴에 대해서 한번 훑어보긴 했었는데 다시한번 복습하는 차원에서 하나하나 정리하는 시간을 갖고 싶었다. 그리고 오늘은 그 첫째 날.

 

오 늘 함께 볼 디자인패턴은 Iterator 패턴이다. 내용의 대부분은 GoF의 디자인패턴 책에서 발췌를 하게될 것임을 밝힌다. 그리고 영문을 한글로 번역을 하게 될텐데 전문번역가가 아니므로 한글 번역본이 이해가 안간다고 느끼면 영문 원본을 읽어보시길 권유한다.

 

그럼 시작해 볼까?

 

우선 GoF의 디자인 패턴은 아래와 같이 크게 3가지 종류로 분류된다.

 Creational Patterns ( 생성 패턴 )

These design patterns provides way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case. 

생성패턴은 객체의 생성로직을 숨기고 new 명령어를 통하지 않고 객체를 생성하는 방법들을 제공한다. 이는 특정 상황에서 어떤 방법으로 객체를 생성해야할지를 결정하는데 있어서 유연성을 제공한다. 


 Structural Patterns ( 구조적 패턴 )

These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. 

구조적 패턴들은 클래스와 객체의 구성에 관여한다.

 

 Behavioral Patterns ( 행위적 패턴 )

These design patterns are specifically concerned with communication between objects.

이 패턴들은 객체들 사이의 커뮤니케이션에 관심을 가진다.

 

이제 살펴볼 Iterator 패턴은 Behavioral 패턴에 속한다. 

Iterator는 자바의 Iterator와 같은 것을 말한다. 사전적 의미로 "반복자"라고 불리는 iterator는 자바의 경우 collection객체에서 사용이 된다. 오라클에서 제공하는 Iterator에 대한 정보는 이곳에서 확인하면된다. 이처럼 앞으로 살펴볼 모든 패턴들은 그 이름에서 이 패턴이 어떤 패턴인지 파악할 수가 있다.

 

Iterator Pattern Structure

 

 


패턴의 목적 :
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

 

Iterator 패턴의 목적은 aggregate object ( ex. List )를 순차적으로 액세스 할 수 있는 방법을 제공하는 것이다. 물론 이 과정에서 개발자는 object가 어떤식으로 구현이 되어있는지는 알 필요가 없으므로 object의 구현부를 노출시키지 않는다.

 

유용성 ( Applicability ) :

· to access an aggregate object's contents without exposing its internal representation.

내부 구현을 노출시키지 않으면서 집약 객체의 내용물에 접근하고자 할 때
· to support multiple traversals of aggregate objects.

집약(집합) 객체들에 대해 다양한 탐색경로(?)를 지원하고자 할 때
· to provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration).

다른 집약(집합)구조들을 탐색하기위한 통일된 인터페이스를 제공하고자 할 때 (즉, 다형적 iteration을 지원하고자 할 때 )

 

등장 인물 :
· Iterator
o defines an interface for accessing and traversing elements.
· ConcreteIterator
o implements the Iterator interface.
o keeps track of the current position in the traversal of the aggregate.
· Aggregate
o defines an interface for creating an Iterator object.
· ConcreteAggregate
o implements the Iterator creation interface to return an instance of the proper ConcreteIterator.

 

장단점 :
1. It supports variations in the traversal of an aggregate.Complex aggregates
may be traversed in many ways. For example, code generation and semantic checking involve traversing parse trees. Code generation may traverse the parse tree inorder or preorder.Iterators make it easy to change the traversal algorithm: Just replace the iterator instance with a different
one. You can also define Iterator subclasses to support new traversals.
2. Iterators simplify the Aggregate interface.Iterator's traversal interface obviates the need for a similar interface in Aggregate, thereby simplifying the aggregate's interface.
3. More than one traversal can be pending on an aggregate.An iterator keeps track of its own traversal state. Therefore you can have more than one traversal in progress at once.


관련 패턴들 : 

Composite : Iterators are often applied to recursive structures such as Composites.
Factory Method : Polymorphic iterators rely on factory methods to instantiate theappropriate Iterator subclass.
Memento is often used in conjunction with the Iterator pattern. An iterator can use a memento to capture the state of an iteration. The iterator stores the memento internally. 

 

 

 


출처 : Design Patterns : Element of Reusable Object Oriented Software ( by GoF, 1994 )