ファクトリパターン

オブジェクトの生成ロジックをカプセル化し、生成方法の詳細を隠蔽するデザインパターン

設計パターンオブジェクト指向

ファクトリパターンとは

ファクトリパターンは、オブジェクトの生成ロジックをカプセル化し、呼び出し側から生成方法の詳細を隠蔽するデザインパターンである。GoF デザインパターンの生成パターンに分類される。

ファクトリの種類

種類 説明
Simple Factory 条件分岐でオブジェクトを生成
Factory Method サブクラスが生成方法を決定
Abstract Factory 関連するオブジェクト群を生成

Simple Factory

type NotificationType = 'email' | 'sms' | 'slack';

interface Notification {
  send(message: string): Promise<void>;
}

function createNotification(type: NotificationType): Notification {
  switch (type) {
    case 'email': return new EmailNotification();
    case 'sms': return new SmsNotification();
    case 'slack': return new SlackNotification();
  }
}

// 呼び出し側は具体的なクラスを知らない
const notification = createNotification('email');
await notification.send('Hello');

AWS サービスのファクトリ

// 環境に応じて異なるクライアントを生成
function createDbClient() {
  const endpoint = process.env.DYNAMODB_ENDPOINT;
  return endpoint
    ? new DynamoDBClient({ endpoint }) // ローカル開発
    : new DynamoDBClient({});          // AWS 環境
}

ファクトリ関数 vs クラス

// ファクトリ関数 (TypeScript で推奨)
function createUser(name: string, role: string) {
  return {
    name,
    role,
    createdAt: new Date(),
    isAdmin: () => role === 'admin',
  };
}

// クラス (Java 的)
class User {
  constructor(public name: string, public role: string) {}
  isAdmin() { return this.role === 'admin'; }
}

TypeScript ではファクトリ関数の方がシンプルで、テストしやすい。

いつファクトリを使うか

ケース 推奨
生成ロジックが複雑 ✅ ファクトリ
条件に応じて異なる型を返す ✅ ファクトリ
単純なオブジェクト生成 ❌ 直接生成で十分
テスト用のモックを差し替えたい ✅ ファクトリ

ファクトリパターンの背景や設計思想は関連書籍に詳しい。

関連用語