the dawn of yuriko hisory

アニメやら漫画関係で何か作りたいものと勉強したことのメモ用

アイマスでデザインパターン Iterator

GitHubリンク

実装クラス一覧

Aggregate - 集合体
Iterator - 数え上げ
Office - 事務所
OfficeIterator - 事務所のアイドルをスキャン
Idol - オフィスに所属するアイドル

各クラス

Iterator
public intrface Iterator {

  // 次のアイドルが存在すればTrue
  public boolean hasNext();

  // 次のアイドルを指し示す
  public Object next();
}
Aggregate
public interface Aggregate {
  public Iterator iterator();
}
Idol
public class Idol {

  // 名前
  private String name;
  // 年齢
  private int age;

  // コンストラクタ
  public Idol(String name, int age){
    this.name = name;
    this.age = age;
  }

  // 自己紹介
  public String selfIntroduction(){
    return name + "," + age + "歳です。";
  }
}  
Office
publc class Office implements Aggregate {
  
  // 事務所に所属しているアイドル
  private Idol[] idols;
  
  // 配列用インデックス
  private int index = 0;

  // コンストラクタ
  public Office(int number){
    this.idols = new Idol[number];
  }

  // Indexからアイドルを取得
  public Idol getIdol(int index){
    return idols[index];
  }

  // アイドルを事務所に迎える
  public void enteringCompany(Idol idol){
    this.idols[index] = idol;
    index++;
  }

  public int getLength(){
    return index;
  }

  // Iteratorの生成
  // thisでOfficeインスタンスを渡す
  @Override
  public Iterator iterator() {
    return new OfficeIterator(this);
  }
}
OfficeIterator
public class OfficeIterator implements Iterator {

  // 事務所
  private Office office;
  
  // インデックス
  private int index;

  // コンストラクタ
  public OfficeIterator(Office office) {
    this.office = office;
    this.index = 0;
  }

  // 事務所の所属アイドルがまだ存在していればTrue
  @Override
  public boolean hasNext() {
    if (index < office.getLength()) return true;

    return false;
  }

  // アイドルの情報を取得している大元
  @Override
  public Object next() {
    Idol idol = office.getIdol(index);
    index++;

    return idol;
  }
}

動作確認

public static void startIterator() {

  // 事務所作るよー
  Office 765Office = new Office(5);

  // アイドルスカウト
  765Office.enteringCompany(new Idol("七尾百合子", 15));
  765Office.enteringCompany(new Idol("高坂海美", 16));
  765Office.enteringCompany(new Idol("佐竹美奈子", 18));
  765Office.enteringCompany(new Idol("周防桃子", 11));
  765Office.enteringCompany(new Idol("田中琴葉", 18));

  // Iteratorインスタンスを作成して、アイドルを順番に呼び出す
  iterator iterator = office.iterator();

  while(iterator.haxNext()){
    Idol idol = (Idol)iterator.next();
    // 自己紹介をする
    System.out.println(idol.selfIntroduction());
  }

}

実行結果

七尾百合子,15歳です。
高坂海美,16歳です。
佐竹美奈子,18歳です。
周防桃子,11歳です。
田中琴葉,18歳です。


765で作るならASメンバーで作ればよかったなと作り終わってから後悔

動き的にはアイドルがいれば引っ張ってきて、いなければ処理終了なだけ
あまり意識してないけど拡張forの内部とかでIterator使われているらしい