GoF:Factory

公開:2026.06.01(月) 00:36

Factory

GoFのFactory Method(ファクトリーメソッド)は、オブジェクトの生成処理をサブクラスに委譲するデザインパターンです。オブジェクトを生成する「工場(ファクトリー)」の枠組みを親クラスで定義し、具体的な生成を子クラスで行うことで、柔軟性と拡張性を高めます。

・結合度の低下: クラスを利用する側が「どの具体的なクラスをインスタンス化するか」を直接知る必要がなくなります。
・拡張性の向上: 新しい種類の製品(例:InvoiceDocument)を追加したい場合、既存のコードを変更せず、新しい製品クラスとそれに対応するクリエイタークラスを追加するだけで済みます。

Visual Basic(VB.NET)実装例

共通のインターフェースを持つ異なるドキュメント(レポートと履歴書)を、それぞれのファクトリークラスで生成する例です。
Module Module1

    ' 1. 製品のインターフェース
    Public Interface IDocument
        Sub Show()
    End Interface

    ' 2. 具体的な製品A
    Public Class ReportDocument
        Implements IDocument
        Public Sub Show() Implements IDocument.Show
            Console.WriteLine("レポートドキュメントを作成しました。")
        End Sub
    End Class

    ' 3. 具体的な製品B
    Public Class ResumeDocument
        Implements IDocument
        Public Sub Show() Implements IDocument.Show
            Console.WriteLine("履歴書ドキュメントを作成しました。")
        End Sub
    End Class

    ' 4. 生成を司る抽象クラス(Factory Method パターンの核)
    Public MustInherit Class DocumentCreator
        ' サブクラスに実装させる生成メソッド
        Protected MustOverride Function FactoryMethod() As IDocument

        ' インスタンスの生成を利用する処理
        Public Sub DoSomething()
            Dim doc As IDocument = FactoryMethod()
            Console.WriteLine("ドキュメントの処理を開始します。")
            doc.Show()
        End Sub
    End Class

    ' 5. 具体的な生成者A(レポート用)
    Public Class ReportCreator
        Inherits DocumentCreator
        Protected Overrides Function FactoryMethod() As IDocument
            Return New ReportDocument()
        End Function
    End Class

    ' 6. 具体的な生成者B(履歴書用)
    Public Class ResumeCreator
        Inherits DocumentCreator
        Protected Overrides Function FactoryMethod() As IDocument
            Return New ResumeDocument()
        End Function
    End Class

    ' 実行テスト
    Public Sub Test()
        ' レポートを作成するファクトリーを使用
        Dim creatorA As DocumentCreator = New ReportCreator()
        creatorA.DoSomething()

        ' 履歴書を作成するファクトリーを使用
        Dim creatorB As DocumentCreator = New ResumeCreator()
        creatorB.DoSomething()
    End Sub

End Module


0 件のコメント:

その他の記事