Red > Green > Refactor > Red

cycle is based on desire

インスタンス生成の分岐(Java)

stuff → staff

思い出し用に書き残し

src
  |
  +-- jp.ymatsukawa
      +-- Main.java
      |
      +-- stuff
      |    |
      |    + -- Stuff.java
      +-- stuffType
            |
            + -- StuffType.java
            + -- Manager.java
            + -- Engineer.java

jp.ymatsukawa/Main.java

package jp.ymatsukawa;

import jp.ymatsukawa.stuff.Stuff;
import jp.ymatsukawa.stuffType.StuffType;

public class Main {
  public static void main(String[] args) {
    Stuff engineer = new Stuff(StuffType.ENGINEER);
    Stuff manager  = new Stuff(StuffType.MANAGER);
    System.out.println(engineer.payAmount()); /* 30 */
    System.out.println(manager.payAmount()); /* 40 */
  }
}

jp.ymatsukawa/stuff/Stuff.java

package jp.ymatsukawa.stuff;

import jp.ymatsukawa.stuffType.Engineer;
import jp.ymatsukawa.stuffType.Manager;
import jp.ymatsukawa.stuffType.StuffType;

public class Stuff {
  private StuffType stuffType;

  public Stuff(int stuffCode) {
    switch(stuffCode) {
      case StuffType.ENGINEER:
        this.stuffType = new Engineer();
        break;
      case StuffType.MANAGER:
        this.stuffType = new Manager();
        break;
      default:
        new RuntimeException();
    }
  }

  public int payAmount() {
    return stuffType.payAmount(this);
  }
  public int getMonthlySalary() {
    return 20;
  }
}

jp.ymatsukawa/stuffType/StuffType.java

package jp.ymatsukawa.stuffType;

import jp.ymatsukawa.stuff.Stuff;

public abstract class StuffType {
  public static final int ENGINEER = 0;
  public static final int MANAGER  = 1;

  public abstract int payAmount(Stuff stuff);
}

jp.ymatsukawa/stuffType/Manager.java

package jp.ymatsukawa.stuffType;

import jp.ymatsukawa.stuff.Stuff;

public class Manager extends StuffType {
  public int payAmount(Stuff stuff) {
    return stuff.getMonthlySalary() + 20;
  }
}

jp.ymatsukawa/stuffType/Engineer.java

package jp.ymatsukawa.stuffType;

import jp.ymatsukawa.stuff.Stuff;

public class Engineer extends StuffType {
  public int payAmount(Stuff stuff) {
    return stuff.getMonthlySalary() + 10;
  }
}