LoginSignup
0
1

JavaScriptデザインパターン入門【ファクトリパターン】

Last updated at Posted at 2023-07-30

こんにちは!今日はTypeScriptを使用してGoF(Gang of Four)のファクトリパターンを解説します。この記事では、基本的なファクトリパターンから抽象ファクトリパターンまで、具体的なコードサンプルを交えて説明します。デザインパターン初心者の方でも理解しやすいように詳しく解説しますので、ぜひ最後までお読みください。

目次

  1. ファクトリパターンとは
  2. 基本的なファクトリパターン
  3. 抽象ファクトリパターン
  4. まとめ

ファクトリパターンとは

ファクトリパターンは、クラスのインスタンス生成を専門の「ファクトリ」クラスに委ねることで、オブジェクトの作成とその使用を分離するデザインパターンです。

基本的なファクトリパターン

まずは基本的なファクトリパターンから見ていきましょう。以下の例は、ToyBookという異なる2つのタイプの製品を生成するシンプルなProductFactoryです。

interface Product {
    description: string;
}

class Toy implements Product {
    description = 'A toy';
}

class Book implements Product {
    description = 'A book';
}

class ProductFactory {
    createProduct(type: string): Product {
        if (type === 'toy') {
            return new Toy();
        }
        if (type === 'book') {
            return new Book();
        }
        throw new Error('Invalid product type');
    }
}

抽象ファクトリパターン

次に、より進んだファクトリパターン、具体的には「抽象ファクトリパターン」を見てみましょう。以下の例では、異なるAPIエンドポイントにリクエストを行うためのクライアントを生成するファクトリを作成します。

interface ApiClient {
    get: (path: string) => Promise<any>;
}

class UserApiClient implements ApiClient {
    get = async (path: string) => {
        // User APIに関するリクエスト処理
        console.log(`User API request to ${path}`);
    };
}

class ProductApiClient implements ApiClient {
    get = async (path: string) => {
        // Product APIに関するリクエスト処理
        console.log(`Product API request to ${path}`);
    };
}

interface ApiClientFactory {
    createApiClient(): ApiClient;
}

class UserApiClientFactory implements ApiClientFactory {
    createApiClient(): ApiClient {
        return new UserApiClient();
    }
}

class ProductApiClientFactory implements ApiClientFactory {
    createApiClient(): ApiClient {
        return new ProductApiClient();
    }
}

// 使用例
let factory: ApiClientFactory = new UserApiClientFactory();
let apiClient = factory.createApiClient();
apiClient.get('/users');

factory = new ProductApiClientFactory();
apiClient = factory.createApiClient();
apiClient.get('/products');

まとめ

以上が、TypeScriptでのGoFのファクトリパターンの解説でした。このパターンは、オブジェクトの作成をカプセル化することで、システムのフレキシビリティと再利用性を高める役割を果たします。具体的なクラスのインスタンスを作成する責任をファクトリクラスが担うことで、コードの依存性が減少し、メンテナンスが容易になります。

初心者から上級者まで、これからTypeScriptでファクトリパターンを使ってみようと考えている方々が何か参考になれば幸いです。お読みいただきありがとうございました!

以上です!いいねとコメントは励みになりますので、よろしければお願いします。また質問やコメントもお気軽にどうぞ!

0
1
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
0
1