이터레이터 패턴이란?
- 데이터의 형식에 상관 없이 동일한 방법으로 데이터를 하나씩 조회해볼 수 있는 패턴
- 배열을 하나씩 꺼내보는 방법과 Map을 하나씩 꺼내보는 방식은 다름.
- 집합체 클래스를 배열처럼 순차적으로 조회해볼 수 있다.
@Getter
@Setter
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
- 학생 클래스
public interface Aggregate {
Iterator createIterator();
}
- Iterator 역할을 만들어내는 인터페이스를 결정
public class School implements Aggregate{
private Student[] students;
private int num = 0;
public School(int size) {
students = new Student[size];
}
public Student getStudent(int index) {
return students[index];
}
public int getLength(){
return num;
}
public void addStudent(Student student) {
if (num < students.length){
this.students[num] = student;
num++;
} else {
System.out.println("정원 초과입니다.");
}
}
@Override
public Iterator createIterator() {
return new SchoolIterator(this);
}
}
- 학생들이 있는 학교 역할 클래스
- Aggregate의 구현체
- 학생들을 조회할 수 있는 SchoolIterator를 생성한다.
public class SchoolIterator implements Iterator{
private School school;
private int index;
public SchoolIterator(School school) {
this.school = school;
this.index = 0;
}
@Override
public boolean hasNext() {
if(index < school.getLength())
{ return true;}
else
{ return false;}
}
@Override
public Object next() {
Student student = school.getStudent(index);
index++;
return student;
}
}
- Iterator의 구현체
- School에서 생성돼 실제로 School내의 검색을 수행한다
public class LetsGoSchool {
public static void main(String[] args) {
School school = new School(4);
school.addStudent(new Student("윤정", 20));
school.addStudent(new Student("인혁", 20));
school.addStudent(new Student("진호", 20));
school.addStudent(new Student("건영", 20));
Iterator iterator = school.createIterator();
while(iterator.hasNext()){
Student student = (Student) iterator.next();
System.out.println(student.getName() + " " + student.getAge());
}
}
}
- hasNext를 통해 전체를 조회해볼 수 있다.
*** 자바 Collection 인터페이스에서 이미 집합체를 조작하기 위한 여러 유용한 메소드를 갖고 있다.
-> 그 중 하나가 iterator()
public interface Iterator {
boolean hasNext();
Object next();
void remove();
}
ArrayList<Integer> list = new ArrayList<Integer>();
Iterator<Integer> itr = list.iterator();
while( itr.hasNext() ){
list.get( itr.next() );
}
'Computer Science > Design Pattern' 카테고리의 다른 글
[디자인 패턴] 데코레이터 패턴 (feat. Spring) (0) | 2024.01.04 |
---|---|
[디자인 패턴] 프록시 패턴 (feat. Spring) (0) | 2023.12.28 |
[디자인 패턴] 전략 패턴 (feat. Spring) (0) | 2023.12.22 |
[디자인 패턴] 템플릿 메서드 패턴 (feat. Spring) (0) | 2023.12.14 |
팩토리 패턴 (0) | 2022.07.05 |