Red > Green > Refactor > Red

cycle is based on desire

インスタンス生成の分岐: Factory method と interface

stuff → staff

f:id:mat5ukawa:20150918221640p:plain

  • 素晴らしい 今後この手法を参考にする
    • クライアント側がプロダクション内部のことを気にしなくて良い
    • プロダクション側が固定値でインスタンス生成の分岐可能
src
  |
  +-- jp.ymatsukawa
      +-- Main.java
      |
      +-- stuff
           |
           + -- Creator.java (interface)
           + -- StuffCreator.java
           + -- StuffType (enum)
           + -- Stuff.java (interface)
           + -- 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;
import jp.ymatsukawa.stuff.StuffType;

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

jp.ymatsukawa/stuff/Creator.java

package jp.ymatsukawa.stuff;

public interface Creator {
  public Stuff createStuff(StuffType stuffType);
}

jp.ymatsukawa/stuff/StuffCreator.java

package jp.ymatsukawa.stuff;

public class StuffCreator implements Creator {
  @Override
  public Stuff createStuff(StuffType stuffType) {
    switch(stuffType) {
      case MANAGER:
        return new Manager();
      case ENGINEER:
        return new Engineer();
      default:
        throw new RuntimeException("Illegal stuffType allocation");
    }
  }
}

jp.ymatsukawa/stuff/StuffType.java

package jp.ymatsukawa.stuff;

public enum StuffType {
  MANAGER, ENGINEER;
}

jp.ymatsukawa/stuff/Stuff.java

package jp.ymatsukawa.stuff;

public interface Stuff {
  public int getMonthlySalary();
}

jp.ymatsukawa/stuff/Manager.java

package jp.ymatsukawa.stuff;

public class Manager implements Stuff {
  public int getMonthlySalary() {
    return 40;
  }
}

jp.ymatsukawa/stuff/Engineer.java

package jp.ymatsukawa.stuff;

public class Engineer implements Stuff {
  @Override
  public int getMonthlySalary() {
    return 30;
  }
}

technical reference from

github.com

stackoverflow.com

thanks