반복자 패턴 소개: 객체 컬렉션을 효율적으로 순회하는 디자인 패턴
반복자 패턴이 뭘까?
반복자 패턴이란 내가 원하는 어떠한 class 들이 쫙 있다고 했을때 생성된 그 모든 친구들을 쫙 돌고 싶을때 사용 할 수 있는 패턴이다. 뭔가 전체적으로 추가하고싶은게 있다거나 전체적으로 특정 행동을 취하고 싶을때 사용하면 된다! 구현도 아주 쉽다! 예를 들면 아래와 같은 class 가 있다고 해보자!
1
2
3
4
5
6
7
8
9
10
11
public class Phone {
private String id;
public Phone(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
여러곳에서 book 이 계속 생길것이고 우리는 여기에서 여러개의 book을 한번에 iterator로 돌수있도록 만들고 싶은 것이다!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public interface Aggregate {
Iterator createIterator();
}
public class PhoneAggregate implements Aggregate {
private List<Phone> phoneList;
public BookShelf(int size) {
phoneList = new ArrayList<Phone>();
}
public int getLength() {
return phoneList.size();
}
public Phone getPhone(int index) {
return phoneList.get(index);
}
public void addPhone(Phone phone) {
phoneList.add(phone);
}
@Override
public Iterator createIterator() {
return new PhoneAggregateIterator(this);
}
}
public class PhoneAggregateIterator implements Iterator<Phone> {
private PhoneAggregate phoneAggregate;
private int index = 0;
public PhoneAggregateIterator(PhoneAggregate phoneAggregate) {
this.phoneAggregate = phoneAggregate;
}
@Override
public boolean hasNext() {
return index < bookShelf.getLength();
}
@Override
public Phone next() {
return phoneAggregate.getPhone(index++);
}
}
이렇게 구조를 잡으면 Phone 을 생성한다음 PhoneAggregate 여기에 넣어주기만 하면 언제든지 전체 phone List 를 iterate 할 수 있게 된다!
사용은 다음과 같이 하면 된다!
1
2
3
4
5
6
7
8
9
10
11
12
13
PhoneAggregate phoneAggregate = new PhoneAggregate();
Phone phone1 = new Phone("id");
Phone phone2 = new Phone("id_");
phoneAggregate.addPhone(phone1);
phoneAggregate.addPhone(phone2);
Iterator it = phoneAggregate.createIterator();
while (it.hasNext()) {
Phone phone = (Phone) it.next();
// 작업
}
어떤 상황에서 사용하면 좋을까?
작업 하는 사람은 안의 컬렉션이 어떤 동작을 하는지 크게 신경쓰지 않고 전체를 돌고 싶을때 아주 쉽게 사용 할 수 있다는 장점이 있다! 모든 항목에 접근하는 작업을 아주 쉽게 할 수 있다는 장점도 있다!
This post is licensed under CC BY 4.0 by the author.