0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

デザインパターン Iterator(typescript)

0
Posted at

Iterator パターンは、要素の集まりを保有するオブジェクトの各要素に順番にアクセスする方法を提供するためのパターン

何らかの集約体が必ずAggregate インタフェースを実装する
Aggregate とは、集約を意味する単語で、Aggregate インタフェースでは Iterator インタフェースの実装クラスを返す、iterator() というメソッドを定義している
image.png

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()

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?