TypeScript デザインパターン

デザインパターンはソフトウェア開発において実証された解決策であり、保守性が高く拡張可能なコードを書くのに役立ちます。

TypeScriptの型システムにより、多くの古典的なデザインパターンを型安全な方法で実装できます。


SVG図解:デザインパターンの分類 背景 タイトル デザインパターンの分類 生成型 生成型パターン Factory | Singleton | Builder 構造型 構造型パターン Decorator | Adapter | Proxy 振る舞い型 振る舞い型パターン Observer | Strategy | Command TypeScript 特有 TypeScript 特有のパターン 型安全な依存性注入 | ジェネリックファクトリー | 条件型の選択 利点 TypeScriptの利点:コンパイル時の型チェック + IDEのスマートヒント + ランタイムパフォーマンス

なぜデザインパターンが必要なのか

デザインパターンは先人たちがまとめたコード整理の経験であり、一般的なソフトウェア設計の問題を解決できます。

デザインパターンを使用することで、コードが理解しやすく保守しやすくなり、チームでの協業も容易になります。

TypeScriptの型システムにより、これらのパターンはより堅牢になり、エラーはコンパイル時に発見できます。

概念:デザインパターンとは、ソフトウェア設計における一般的な問題に対する再利用可能な解決策であり、コード設計の経験の集大成です。


シングルトンパターン (Singleton)

クラスのインスタンスが1つだけであることを保証し、グローバルなアクセスポイントを提供します。

実例

// シングルトンパターン:インスタンスが1つだけであることを保証
class Singleton {
    // シングルトンのインスタンスを格納
    private static instance: Singleton;
    private static _data: string = "";

    // プライベートコンストラクタ。外部からのインスタンス化を防ぐ
    private constructor() {}

    // シングルトンのインスタンスを取得する静的メソッド
    public static getInstance(): Singleton {
        if (!Singleton.instance) {
            Singleton.instance = new Singleton();
        }
        return Singleton.instance;
    }

    // データを設定
    public setData(data: string): void {
        Singleton._data = data;
    }

    // データを取得
    public getData(): string {
        return Singleton._data;
    }
}

// シングルトンパターンのテスト
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();

// 同じインスタンスであることを検証
console.log("同じインスタンス: " + (instance1 === instance2));

instance1.setData("Hello Singleton");
console.log("データ: " + instance2.getData());

実行結果:

是同一实例: true
数据: Hello Singleton

プライベートコンストラクタ:コンストラクタをprivateにすることで、外部がnewを使ってインスタンスを作成するのを防ぎます。


ファクトリーパターン (Factory)

ジェネリックファクトリーを使用して、型安全なオブジェクトインスタンスを作成します。

実例

// 製品インターフェースを定義
interface Product {
    name: string;
    price: number;
    getDescription(): string;
}

// 具体的な製品:電子製品
class ElectronicProduct implements Product {
    constructor(
        public name: string,
        public price: number,
        public warranty: number
    ) {}

    getDescription(): string {
        return `${this.name} - ¥${this.price} (保証${this.warranty}年)`;
    }
}

// 具体的な製品:衣類
class ClothingProduct implements Product {
    constructor(
        public name: string,
        public price: number,
        public size: string
    ) {}

    getDescription(): string {
        return `${this.name} - ¥${this.price} (サイズ: ${this.size})`;
    }
}

// ファクトリークラス
class ProductFactory {
    // ジェネリックファクトリーメソッド
    static create<T extends Product>(
        type: new (...args: any[]) => T,
        ...args: any[]
    ): T {
        return new type(...args);
    }
}

// ファクトリーを使用して製品を作成
const laptop = ProductFactory.create(ElectronicProduct, "ノートパソコン", 5999, 2);
const shirt = ProductFactory.create(ClothingProduct, "Tシャツ", 199, "L");

console.log(laptop.getDescription());
console.log(shirt.getDescription());

ジェネリックファクトリー:ジェネリックの制約を使用して、具体的な製品型を返すことを保証します。


デコレーターパターン (Decorator)

デコレーターを使用して、オブジェクトに機能を動的に追加します。

実例

// 基本のコーヒーインターフェース
interface Coffee {
    getCost(): number;
    getDescription(): string;
}

// 基本のコーヒー実装
class SimpleCoffee implements Coffee {
    getCost(): number {
        return 10;
    }

    getDescription(): string {
        return "コーヒー";
    }
}

// デコレーターの基底クラス
abstract class CoffeeDecorator implements Coffee {
    constructor(protected coffee: Coffee) {}

    getCost(): number {
        return this.coffee.getCost();
    }

    getDescription(): string {
        return this.coffee.getDescription();
    }
}

// ミルクデコレーター
class MilkDecorator extends CoffeeDecorator {
    getCost(): number {
        return this.coffee.getCost() + 2;
    }

    getDescription(): string {
        return this.coffee.getDescription() + ", ミルク";
    }
}

// シュガーデコレーター
class SugarDecorator extends CoffeeDecorator {
    getCost(): number {
        return this.coffee.getCost() + 1;
    }

    getDescription(): string {
        return this.coffee.getDescription() + ", シュガー";
    }
}

// デコレーターを使用
let coffee: Coffee = new SimpleCoffee();
console.log(coffee.getDescription() + " - ¥" + coffee.getCost());

coffee = new MilkDecorator(coffee);
console.log(coffee.getDescription() + " - ¥" + coffee.getCost());

coffee = new SugarDecorator(coffee);
console.log(coffee.getDescription() + " - ¥" + coffee.getCost());

デコレーター:元のクラスを変更せずに機能を動的に追加でき、TypeScriptの実験的機能です。


オブザーバーパターン (Observer)

オブジェクト間の1対多の依存関係を定義し、オブジェクトの状態が変わると、すべての依存者に通知が届きます。

実例

// オブザーバーインターフェース
interface Observer {
    update(message: string): void;
}

// サブジェクト(主題)インターフェース
interface Subject {
    attach(observer: Observer): void;
    detach(observer: Observer): void;
    notify(): void;
}

// 具体的なサブジェクト:メッセージセンター
class MessageCenter implements Subject {
    private observers: Observer[] = [];
    private message: string = "";

    // オブザーバーを追加
    attach(observer: Observer): void {
        this.observers.push(observer);
    }

    // オブザーバーを削除
    detach(observer: Observer): void {
        const index = this.observers.indexOf(observer);
        if (index > -1) {
            this.observers.splice(index, 1);
        }
    }

    // すべてのオブザーバーに通知
    notify(): void {
        for (const observer of this.observers) {
            observer.update(this.message);
        }
    }

    // メッセージを配信
    publish(message: string): void {
        this.message = message;
        console.log("メッセージを配信: " + message);
        this.notify();
    }
}

// 具体的なオブザーバー:ユーザー
class UserObserver implements Observer {
    constructor(public name: string) {}

    update(message: string): void {
        console.log(`[${this.name}]メッセージを受信: ${message}`);
    }
}

// オブザーバーパターンを使用
const center = new MessageCenter();

const user1 = new UserObserver("ユーザーA");
const user2 = new UserObserver("ユーザーB");

center.attach(user1);
center.attach(user2);

center.publish("新機能がリリースされました!");

疎結合:オブザーバーパターンは、サブジェクトとオブザーバー間の疎結合を実現します。


ストラテジーパターン (Strategy)

一連のアルゴリズムを定義し、それらを1つずつカプセル化して、相互に置き換えられるようにします。

実例

// 支払いストラテジーインターフェース
interface PaymentStrategy {
    pay(amount: number): void;
}

// WeChat Payストラテジー
class WechatPayStrategy implements PaymentStrategy {
    pay(amount: number): void {
        console.log(`WeChat Payで支払い ¥${amount}`);
    }
}

// Alipayストラテジー
class AlipayStrategy implements PaymentStrategy {
    pay(amount: number): void {
        console.log(`Alipayで支払い ¥${amount}`);
    }
}

// 銀行カードストラテジー
class CardPayStrategy implements PaymentStrategy {
    pay(amount: number): void {
        console.log(`銀行カードで支払い ¥${amount}`);
    }
}

// 支払いコンテキスト
class PaymentContext {
    private strategy: PaymentStrategy;

    constructor(strategy: PaymentStrategy) {
        this.strategy = strategy;
    }

    // 支払いストラテジーを設定
    setStrategy(strategy: PaymentStrategy): void {
        this.strategy = strategy;
    }

    // 支払いを実行
    pay(amount: number): void {
        this.strategy.pay(amount);
    }
}

// ストラテジーパターンを使用
const context = new PaymentContext(new WechatPayStrategy());
context.pay(100);

context.setStrategy(new AlipayStrategy());
context.pay(200);

context.setStrategy(new CardPayStrategy());
context.pay(300);

アルゴリズムの切り替え:ストラテジーパターンは実行時にアルゴリズムを切り替えられるため、非常に柔軟です。


依存性注入 (Dependency Injection)

コンストラクタを通じて依存関係を注入する、TypeScriptで最も一般的なパターンの1つです。

実例

// サービスインターフェースを定義
interface Logger {
    log(message: string): void;
}

interface Storage {
    save(key: string, data: any): void;
}

// 具体的なサービスの実装
class ConsoleLogger implements Logger {
    log(message: string): void {
        console.log("[ログ]: " + message);
    }
}

class LocalStorage implements Storage {
    save(key: string, data: any): void {
        console.log(`保存 ${key}: ${JSON.stringify(data)}`);
        localStorage.setItem(key, JSON.stringify(data));
    }
}

// 依存性注入を使用したサービス
class UserService {
    constructor(
        private logger: Logger,
        private storage: Storage
    ) {}

    createUser(name: string): void {
        const user = { name, createdAt: new Date() };
        this.logger.log("ユーザー作成: " + name);
        this.storage.save("user", user);
    }
}

// 依存関係を注入
const logger = new ConsoleLogger();
const storage = new LocalStorage();
const userService = new UserService(logger, storage);

userService.createUser("Alice");

依存性逆転:依存性注入により、高レベルモジュールが低レベルモジュールに依存せず、抽象インターフェースに依存するようになります。


ビルダーパターン (Builder)

複雑なオブジェクトの構築とその表現を分離し、同じ構築プロセスで異なる表現を作成できるようにします。

実例

// ビルダーインターフェース
interface Builder<T> {
    build(): T;
}

// 複雑なオブジェクト:ユーザー設定
interface UserConfig {
    name: string;
    email: string;
    age?: number;
    role?: string;
    theme?: string;
}

// ユーザー設定ビルダー
class UserConfigBuilder implements Builder<UserConfig> {
    private config: Partial<UserConfig> = {};

    setName(name: string): this {
        this.config.name = name;
        return this;
    }

    setEmail(email: string): this {
        this.config.email = email;
        return this;
    }

    setAge(age: number): this {
        this.config.age = age;
        return this;
    }

    setRole(role: string): this {
        this.config.role = role;
        return this;
    }

    setTheme(theme: string): this {
        this.config.theme = theme;
        return this;
    }

    build(): UserConfig {
        if (!this.config.name || !this.config.email) {
            throw new Error("Name and email are required");
        }
        return this.config as UserConfig;
    }
}

// ビルダーを使用
const builder = new UserConfigBuilder();
const config = builder
    .setName("Alice")
    .setEmail("alice@example.com")
    .setAge(25)
    .setRole("admin")
    .setTheme("dark")
    .build();

console.log("ユーザー設定:", JSON.stringify(config, null, 2));

チェーン呼び出し:ビルダーパターンはチェーン呼び出しに対応しており、コードがより簡潔で読みやすくなります。


注意事項

  • 型安全性:TypeScriptの型システムを活用して、パターン実装の安全性を確保します
  • 使いすぎない:本当に必要なときだけデザインパターンを使用します
  • シンプルに保つ:シンプルな解決策を優先します
  • チームの合意:チーム内でデザインパターンの使用を統一します

ベストプラクティス:デザインパターンはツールであり、教義ではありません。プロジェクトの実際の状況に合ったパターンを選びましょう。


まとめ

デザインパターンはコード整理における重要な経験です。

  • シングルトンパターン:クラスのインスタンスが1つだけであることを保証
  • ファクトリーパターン:オブジェクト作成プロセスをカプセル化
  • デコレーターパターン:機能を動的に追加
  • オブザーバーパターン:1対多の依存関係
  • ストラテジーパターン:アルゴリズムの置き換えが可能
  • 依存性注入:依存関係の疎結合化

アドバイス:デザインパターンを理解して実践に応用することで、よりエレガントで保守しやすいコードを書くことができます。

その他の拡張