Iterator パターンは、要素の集まりを保有するオブジェクトの各要素に順番にアクセスする方法を提供するためのパターン
何らかの集約体が必ずAggregate インタフェースを実装する
Aggregate とは、集約を意味する単語で、Aggregate インタフェースでは Iterator インタフェースの実装クラスを返す、iterator() というメソッドを定義している

interface Aggregate {
itereter(): Itereter
}
interface Itereter {
hasNext(): boolean;
next(): Object;
}
class Student {
name: string;
sex: number; //male:1 female:2
constructor(name: string, sex: number) {
this.name = name;
this.sex = sex;
}
getName() {
return this.name;
}
getSex() {
return this.sex
}
}
class StudentList implements Aggregate{
last: number = 0;
students: Student[];
constructor() {
this.students = [];
}
public getStudentAt(last: number): Student {
return this.students[last];
}
get getLength() {
return this.last
}
public add(student: Student): void {
this.students[this.last] = student;
this.last++;
}
public itereter(): Itereter {
return new MyStudentIterator(this)
}
}
class MyStudentIterator implements Itereter {
index: number
myStudentList: StudentList
constructor(list: StudentList) {
this.index = 0;
this.myStudentList = list
}
hasNext(): boolean {
if (this.index < this.myStudentList.getLength) {
return true
}
else {
return false;
};
};
next(): Object {
const s = this.myStudentList.getStudentAt(this.index);
this.index++;
return s
}
}
function Main() {
const myStudentList: StudentList = new StudentList()
myStudentList.add(new Student('yuki', 1))
myStudentList.add(new Student('aya', 2))
const it = myStudentList.itereter()
while(it.hasNext()){
console.log(it.next())
}
}
Main()