Factory パターン

オブジェクト生成を専用のクラスに委譲するパターン

Factory パターンとは

Factory パターンは、オブジェクトの生成を専用のファクトリクラスに委譲するデザインパターンです。

実装例

interface Animal {
  speak(): string;
}

class Dog implements Animal {
  speak() { return "ワン"; }
}

class Cat implements Animal {
  speak() { return "ニャー"; }
}

class AnimalFactory {
  create(type: "dog" | "cat"): Animal {
    switch (type) {
      case "dog": return new Dog();
      case "cat": return new Cat();
    }
  }
}

メリット

  • 生成ロジックの集約
  • クライアントコードの簡素化
  • 拡張性の向上

目次