LoginSignup
7
6

More than 5 years have passed since last update.

TypeScriptでのFactoryMethod

Posted at

普通だ。

factory_method.ts
interface SlimeStatus {
  name: string;
  hitPoint: number;
  magicPoint: number;
  experiencePoint: number;
  gold: number;
}

var SlimeType = {
  normal: {
    name: "Slime",
    hitPoint: 6,
    magicPoint: 2,
    experiencePoint: 1,
    gold: 1
  },
  she: {
    name: "SheSlime",
    hitPoint: 10,
    magicPoint: 3,
    experiencePoint: 2,
    gold: 1
  },
  metal: {
    name: "MetalSlime",
    hitPoint: 4,
    magicPoint: 999,
    experiencePoint: 2010,
    gold: 14
  },
  liquidMetal: {
    name: "LiquidMetalSlime",
    hitPoint: 8,
    magicPoint: 999,
    experiencePoint: 20100,
    gold: 21
  } 
};

class Slime {
  name: string;
  hitPoint: number;
  magicPoint: number;
  experiencePoint: number;
  gold: number;

  constructor(status: SlimeStatus) {
    this.name = status.name;
    this.hitPoint = status.hitPoint;
    this.magicPoint = status.magicPoint;
    this.experiencePoint = status.experiencePoint;
    this.gold = status.gold; 
  }

  public static makeNormal(): Slime {
    return new Slime(SlimeType.normal);
  }

  public static makeShe(): Slime {
    return new Slime(SlimeType.she);
  }

  public static makeMetal(): Slime {
    return new Slime(SlimeType.metal);
  }

  public static makeLiquidMetal(): Slime {
    return new Slime(SlimeType.liquidMetal);
  }
}

module Runner {
  function viewStatus(slime: Slime): void {
    console.log("Name is: " + slime.name);
    console.log("Hit Point is: " + slime.hitPoint);
    console.log("Magic Point is: " + slime.magicPoint);
    console.log("Experience Point is: " + slime.experiencePoint);
    console.log("Gold is: " + slime.gold);
  }

  export function blame() {
    var slimes: Slime[] = [
      Slime.makeNormal(),
      Slime.makeShe(),
      Slime.makeMetal(),
      Slime.makeLiquidMetal()
    ];

    for(var i = 0; i < slimes.length; i++) { 
      console.log("---------------");
      viewStatus(slimes[i]);
    }
  }
}

Runner.blame();

結果

---------------
Name is: Slime
Hit Point is: 6
Magic Point is: 2
Experience Point is: 1
Gold is: 1
---------------
Name is: SheSlime
Hit Point is: 10
Magic Point is: 3
Experience Point is: 2
Gold is: 1
---------------
Name is: MetalSlime
Hit Point is: 4
Magic Point is: 999
Experience Point is: 2010
Gold is: 14
---------------
Name is: LiquidMetalSlime
Hit Point is: 8
Magic Point is: 999
Experience Point is: 20100
Gold is: 21

やはり、

interfaceでアクセス権(public, private)やstaticなどの定義できるといいんだけどな...
抽象クラス書くのめんどうくさいけど本来のTypeScriptを使う目的としては要らない場面なのかも。
(今回はFactoryMethodをもたせているClassはBaseからの継承などしていない)

7
6
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
7
6