Red > Green > Refactor > Red

cycle is based on desire

インスタンス生成の分岐: factory method パターン

stuff → staff

元: インスタンス生成の分岐(Java) - Red > Green > Refactor > Red

自分に一番響く設計を手当たり次第

f:id:mat5ukawa:20150917000528p:plain

f:id:mat5ukawa:20150917000542p:plain


デザインパターンの Factory method より (記事中では Factory > Creator)

src
  |
  +-- jp.ymatsukawa
      +-- Main.java
      |
      +-- stuff
           |
           + -- Creator.java
           + -- StuffCreator.java
           + -- Stuff.java
           + -- Manager.java
           + -- Engineer.java

jp.ymatsukawa/Main.java

package jp.ymatsukawa;

import jp.ymatsukawa.stuff.Creator;
import jp.ymatsukawa.stuff.Stuff;
import jp.ymatsukawa.stuff.StuffCreator;

public class Main {
  public static void main(String[] args) {
    Creator stuffCreator = new StuffCreator();
    Stuff manager  = stuffCreator.create("manager");
    Stuff engineer = stuffCreator.create("engineer");
    System.out.println(manager.getMonthlySalary()); // 40
    System.out.println(engineer.getMonthlySalary()); // 30
  }
}

jp.ymatsukawa/stuff/Creator.java

package jp.ymatsukawa.stuff;

public abstract class Creator {
  public Stuff create(String stuffCode) {
    Stuff stuff = this.createStuff(stuffCode);
    return stuff;
  }

  protected abstract Stuff createStuff(String stuffCode);
}

jp.ymatsukawa/stuff/StuffCreator.java

package jp.ymatsukawa.stuff;

public class StuffCreator extends Creator {
  public Stuff createStuff(String stuffName) {
    switch(stuffName) {
      case "manager":
        return new Manager();
      case "engineer":
        return new Engineer();
      default:
        throw new RuntimeException();
    }
  }
}

jp.ymatsukawa/stuff/Stuff.java

package jp.ymatsukawa.stuff;

public abstract class Stuff {
  private final int baseSalary = 20;
  public abstract int getMonthlySalary();
  protected int getBaseSalary() {
    return this.baseSalary;
  }
}

jp.ymatsukawa/stuff/Manager.java

package jp.ymatsukawa.stuff;

public class Manager extends Stuff {
  public int getMonthlySalary() {
    return this.getBaseSalary() + 20;
  }
}

jp.ymatsukawa/stuff/Engineer.java

package jp.ymatsukawa.stuff;

public class Engineer extends Stuff {
  public int getMonthlySalary() {
    return this.getBaseSalary() + 10;
  }
}