C++におけるファクトリーパターンと抽象ファクトリーパターンの実装

ソフトウェア設計において、ファクトリーパターンと抽象ファクトリーパターンはオブジェクト生成をカプセル化する重要なクリエーショナルパターンです。これらはクライアントコードからオブジェクト生成ロジックを隠蔽し、システムの拡張性を向上させます。

ファクトリーパターン

オブジェクト生成インターフェイスを定義し、具象クラスのインスタンス化をサブクラスに委譲します。

典型的な課題と解決策

過剰な適用: 不要な場面で使用するとコード複雑性が増加します。

対策: 動的生成が必要な場合や生成ロジックの分離が必要な時のみ適用します。

#include <iostream>

class Widget {
public:
    virtual void render() const = 0;
};

class Button : public Widget {
public:
    void render() const override {
        std::cout << "ボタン描画" << std::endl;
    }
};

class TextField : public Widget {
public:
    void render() const override {
        std::cout << "テキストフィールド描画" << std::endl;
    }
};

class WidgetMaker {
public:
    virtual Widget* create() = 0;
};

class ButtonMaker : public WidgetMaker {
public:
    Widget* create() override {
        return new Button();
    }
};

class TextFieldMaker : public WidgetMaker {
public:
    Widget* create() override {
        return new TextField();
    }
};

int main() {
    WidgetMaker* maker = new ButtonMaker();
    Widget* widget = maker->create();
    widget->render();
    
    delete widget;
    delete maker;
    return 0;
}

抽象ファクトリーパターン

関連オブジェクトのファミリーを生成するインターフェイスを提供し、具象クラスを指定せずに一貫したオブジェクト生成を実現します。

典型的な課題と解決策

拡張困難: 新しい製品ファミリーの追加が困難になる場合があります。

対策: 明確な関連性を持つオブジェクト群の生成に限定して使用します。

#include <iostream>

class UIElement {
public:
    virtual void display() const = 0;
};

class WindowsButton : public UIElement {
public:
    void display() const override {
        std::cout << "Windowsスタイルボタン" << std::endl;
    }
};

class MacButton : public UIElement {
public:
    void display() const override {
        std::cout << "macOSスタイルボタン" << std::endl;
    }
};

class Dialog {
public:
    virtual void show() const = 0;
};

class WindowsDialog : public Dialog {
public:
    void show() const override {
        std::cout << "Windowsダイアログ表示" << std::endl;
    }
};

class MacDialog : public Dialog {
public:
    void show() const override {
        std::cout << "macOSダイアログ表示" << std::endl;
    }
};

class UIFactory {
public:
    virtual UIElement* createButton() = 0;
    virtual Dialog* createDialog() = 0;
};

class WindowsFactory : public UIFactory {
public:
    UIElement* createButton() override {
        return new WindowsButton();
    }
    Dialog* createDialog() override {
        return new WindowsDialog();
    }
};

class MacFactory : public UIFactory {
public:
    UIElement* createButton() override {
        return new MacButton();
    }
    Dialog* createDialog() override {
        return new MacDialog();
    }
};

int main() {
    UIFactory* factory = new MacFactory();
    UIElement* button = factory->createButton();
    Dialog* dialog = factory->createDialog();
    
    button->display();
    dialog->show();
    
    delete button;
    delete dialog;
    delete factory;
    return 0;
}

タグ: C++ デザインパターン ファクトリーパターン 抽象ファクトリーパターン オブジェクト生成

7月1日 19:45 投稿